Abstract
在Angular中,[]用来绑定变量,()用来绑定事件,但还有一种组合形式当’[()]'出现时,表示双向绑定。
语法糖解析
<p [(customVal)]="x"></p>
// 解析后
<p [customVal]="x" (customValChange)="x = $event"></p>
case-弹窗组件
ng g c dialog
dialog.component.html:
<div class="dialog" [hidden]="!visible">
<p>dialog works!</p>
<button (click)="onClose()">点我关闭</button>
</div>
dialog.component.ts:
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.scss'],
})
export class DialogComponent {
@Input() visible = false;
@Output() visibleChange = new EventEmitter<boolean>();
onClose() {
this.visibleChange.emit(false);
}
}
使用弹窗组件:
demo.component.html:
<p>demo works!</p>
<button (click)="visible = true">打开弹窗</button>
<app-dialog [(visible)]="visible"></app-dialog>
demo.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.scss'],
})
export class DemoComponent {
public visible = false;
}
效果:
点击打开能打开,点击关闭则关闭。使用方便。
扩展ngModel指令
通过引入FormsModule模块,对于原生的input,checkbox等表单元素,可以使用[(ngModel)]进行双向绑定。
app.module.ts:
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
],
})
component.html:
<input [(ngModel)]="name" />
{{name}}
component.ts:
public name = '青梅';
效果:
Tip:ngModel内置指令的原理其实就是将表单的value和input事件结合,进行双向绑定。
想要源码的,可以来访问我的代码仓:
https://gitee.com/gao-hui007/my-blogs/blob/master/docs/angular/%E5%8F%8C%E5%90%91%E7%BB%91%E5%AE%9A.md#
转载请备注来源