Angular7教程-04-Angular常用操作(下)

6. 數據雙向綁定

視圖和數據,只要一方發生變化,另一方跟着變化。

好處是不需要在代碼中手動更新視圖,簡化開發,增加代碼內聚性,代碼可讀性更強。

缺點是當綁定的數據層次深、數據量大時,會影響性能。

雙向數據綁定的語法是[(x)].

修改article.component.html中的內容如下:

<input type="text" [(ngModel)] = "content">
{{content}}

當在input框中輸入內容時,插值表達式的位置內容會同時改變。在使用ngModel時需要在app.module.ts中增加FormsModule的引用。修改app.module.ts的內容如下:

//在文件頭部增加如下一行:
import {FormsModule} from "@angular/forms";
//在imports中增加FormsModule
imports: [
	BrowserModule,
	FormsModule  
  ]

7. angular指令操作

7.1 判斷指令

7.1.1 不帶else分支的if指令

article.component.ts中定義一個布爾類型的值,然後定義一個函數,如下:

export class ArticleComponent implements OnInit {
	status = false;
	changeStatus(){
		this.status = true;
	}
}

article.component.html定義內容如下:

<button class="btn btn-sm btn-info" (click)="changeStatus()">更改狀態</button>
<p *ngIf="status">
    默認狀態下這段話是不顯示的,因爲status值爲false,當單擊上面的按鈕,
    把status的值設爲true時,這段話才顯示。
</p>

則頁面顯示效果如<p>標籤中的內容所示。

7.1.2帶else分支的if指令

修改article.component.ts的內容如下:

<p *ngIf="status;else p1">
    默認狀態下這段話是不顯示的,因爲status值爲false。
</p>
<ng-template #p1>
    <p>如果上面那段話不顯示,則表示執行else邏輯,顯示這一段話。</p>
</ng-template>

則頁面上初始化時只顯示第二段話,表明執行的是else邏輯。ng-template指令後面會講到。

7.2 樣式指令

下面是內聯樣式和類樣式的寫法:

<style>
	.bg{
		background-color: pink;
	}
</style>
<p [ngClass]="{bg:true}">這段內容應用的是類樣式。</p>
<p [ngStyle]="{backgroundColor:getColor()}">本段內容樣式是內聯樣式。</p>

頁面顯示效果如下:

在這裏插入圖片描述

7.3 循環指令

article.component.ts中定義一個數組:

export class ArticleComponent implements OnInit {
	articles = ['第一篇文章','第二篇文章', '第三篇文章']
}

article.component.html中通過循環指令輸出數組內容:

<p *ngFor="let article of articles; let i = index">
    {{i}} - {{article}}
</p>

其中的i爲循環下標。頁面效果如下所示:

在這裏插入圖片描述

ng-template的說明

ng-template指令用來定義模板,如下代碼所示:

<ng-template #p1>
    <p>段落內容</p>
</ng-template>

上面定義了一個簡單的模板,id爲p1,別的地方可以通過id來引用這個模板。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章