1. ts文件与html交互
// 在ts文件中声明变量
public title = 'Hello';
// 在html中使用变量(使用两个花括号)
<h1>{{ title }}</h1>
// 绑定html
ts: public h = '<h1>Hello</h1>'
html: <div [innerHTML]="h"></div>
2. *ngFor 循环
// ts中声明一个数组
public arr: string[] = ['1', '2', '3', '4'];
// html中使用 (i为数组的下标)
<ul>
<li *ngFor="let item of arr; let i=index">{{i}}---{{item}}</li>
</ul>
3. *ngIf
ts: public flag: boolean = true;
html: <h1 *ngIf="flag">flag是true时显示</h1>
<h1 *ngIf="!flag">flag是false时显示</h1>
4. *ngSwitch
ts: public flag: string = "2";
html:
<ul *ngSwitch="flag">
<li *ngSwitchCase="1">a</li>
<li *ngSwitchCase="2">b</li>
<li *ngSwitchCase="3">c</li>
<li *ngSwitchDefault>d</li>
</ul>
5. 引入图片
// 本地图片(assets存放的是静态资源)
<img src="assets/xxx/xxx.jpg" />
// 引用外部图片
ts: public picUrl: string = "http://www.xxx.com/xxx/xxx.jpg"
html: <img [src]="picUrl" />
6. 绑定方法
ts:
demo() { console.log('Hello'); }
html:
<button (click)="demo()">按钮</button>
7. 双向数据绑定(使用时需要在根模块中导入 FormsModule)
ts: public data: string = "aaa";
html: <input type="text" [(ngModel)]="data" />
(修改文本框的值, ts中的变量的值会跟着改变, 修改变量的值, 文本框中的内容也会跟着变)
8. ts中获取dom节点, 同样方式也可以获取子组件
在html中, 给元素用#命名, ts中导入ViewChild
html: <div #aaa>...</div>
ts: @ViewChild('aaa') d: any;
9. 父组件给子组件传值
子组件的ts中需要先导入Input, 然后定义变量接收父组件传过来的数据
@Input() msg: any;
父组件调用子组件的地方, 在子组件上写变量并赋值
<app-xxx [msg]="'aaa'"></app-xxx>