zoukankan      html  css  js  c++  java
  • 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来引用这个模板。

  • 相关阅读:
    codeforces 707D-(DFS+bitset)
    codeforces Educational Codeforces Round 16-E(DP)
    codeforces 597C (树状数组+DP)
    codeforces #round363 div2.C-Vacations (DP)
    Codeforces Round #365 (Div. 2)-D Mishka and Interesting sum(树状数组)
    codeforces round367 div2.C (DP)
    June Challenge 2018 Division 2
    Codeforces Round #487 (Div. 2)
    Educational Codeforces Round 45 (Rated for Div. 2)
    [Offer收割]编程练习赛63
  • 原文地址:https://www.cnblogs.com/dwllm/p/9949388.html
Copyright © 2011-2022 走看看