ng new my-app //新建项目
ng generate module home //新建模块
ng generate component home/container //新建组件
ng generate component home/container -t//新建组件,使用template
ng generate class hero //创建一个类
组件扮演着控制器的角色,模板扮演视图的角色
- interpolation自定义插值分隔符
@Component({
selector: 'app-root',
styleUrls: ['./app.component.sass'],
interpolation: ['$', '$'],
template: `<div>$title$</div>`,
})
export class AppComponent {
title = '测试';
}
- 插值和模板表达式--(属性bind-或者[])
@Component({
selector: 'app-root',
styleUrls: ['./app.component.sass'],
template: `
<div [title]="title">{{title+'xxx'}}</div>
<div bind-title="title"></div>
`,
})
export class AppComponent {
title = '测试';
}
- 模板语句--(事件on-或者())
@Component({
selector: 'app-root',
styleUrls: ['./app.component.sass'],
template: `
<div (click)="handleClick($event)">{{title}}</div>
<div on-click="handleClick($event)">
<button [disabled]="isUnchanged">Save</button>
`,
})
export class AppComponent {
title = '测试';
isUnchanged = true;
handleClick(ev){
}
}
- 模板引用变量
@Component({
selector: 'app-root',
styleUrls: ['./app.component.sass'],
template: `
<div (click)="handleClick(divRef)" #divRef>{{title}}</div>
`,
})
export class AppComponent {
title = '测试';
handleClick($el){
console.log($el)
}
}
- 双向绑定--(bindon-或者[()])
@Component({
selector: 'app-root',
styleUrls: ['./app.component.sass'],
template: `
<p>{{username}}</p>
<input type="text" [value]="username" (input)="username = $event.target.value"/>
<input type="text" [(ngModel)]="username"/>
<input type="text" [ngModel]="username" (ngModelChange)="username=$event"/>
`,
})
export class AppComponent {
username = '测试';
}