ngIf與hidden是用來顯示或隱藏Html上的元素
首先,先來試試ngIf
用法很簡單,在你想顯示或隱藏的元素上打上*ngIf="布林判斷"
<div *ngIf="false" >
<input type="text" [(ngModel)]="birthday" />
</div>
當然,*ngIf的等號右側是可以打上在.ts中宣告的變數<div *ngIf="edit" >
<input type="text" [(ngModel)]="birthday" />
</div>
上方變數名稱為edit所以我們到.ts檔中宣告一個edit@Component({
selector: 'my-app',
templateUrl: './Demo/index.html',
})
export class DemoComponent {
name = "kai";
birthday = "11/21";
edit = false;
}
這時後可以先存檔到瀏覽器上看看,會發現看不到任何東西因為當ngif=false時元素會被隱藏,反之則顯示
利用這個特性,我們就可以來做編輯功能切換時的效果
先在html中做一個切換要用的元素,並在上方做一個按鈕來切換
<button (click)="call()">{{text}}</button>
<div>
<div>
姓名:
</div>
<div *ngIf="edit">
<input type="text" [(ngModel)]="name" />
</div>
<div *ngIf="!edit">
{{name}}
</div>
</div>
<div>
<div>
生日:
</div>
<div *ngIf="edit" >
<input type="text" [(ngModel)]="birthday" />
</div>
<div *ngIf="!edit">
{{birthday}}
</div>
</div>
其中,因為我們edit預設是false,那我們輸入框要在按編輯的時後才會顯示所以這邊的*ngIf="edit"
<div *ngIf="edit">
<input type="text" [(ngModel)]="name" />
</div>
另外單純顯示文字是一開始要顯示的,所以這邊的*ngIf="!edit"<div *ngIf="!edit">
{{name}}
</div>
最後就是做一個切換鈕跟函式<button (click)="call()">{{text}}</button>
函式內容則為,點下去edit=!edit自己的相反,即false變true這邊另外要注意的就是,在函式中變數名稱前面要加this.
export class DemoComponent {
name = "kai";
birthday = "11/21";
edit = false;
text = "編輯";
call() {
this.edit = !this.edit;
if (this.text == "編輯") {
this.text = "確定";
} else {
this.text = "編輯";
}
}
}
在上面我再加一個效果,就是按紐文字的變換,看起來比較有感覺如此就完成了一個簡單的編輯表單,馬上就來試試吧
試用完ngIf後我們再用hidden來做同樣的效果吧
這邊直接把所有的*ngIf改成[hidden]
大功告成?不,因為[hidden]=false是隱藏
所以要跟剛剛用ngIf的布林值相反,效果才會一樣
<button (click)=<button (click)="call()">{{text}}</button>
<div>
<div>
姓名:
</div>
<div [hidden]="!edit">
<input type="text" [(ngModel)]="name" />
</div>
<div [hidden]="edit">
{{name}}
</div>
</div>
<div>
<div>
生日:
</div>
<div [hidden]="!edit">
<input type="text" [(ngModel)]="birthday" />
</div>
<div [hidden]="edit">
{{birthday}}
</div>
</div>"call()">{{text}}</button>
趕快來試試,效果是不是一樣呢?雖然表面上的效果是一樣的,但可以開啟Chrome的F12
可以發現,ngIf是會新增移除Dom元素
但hidden只是單純隱藏而已,Dom元素還在Html上
初學時看教學文章,即使一個小步驟沒打,也容易會不知道怎麼往下做
故以下影片是一步一步做的,以補文章的不足
0 意見:
張貼留言