在使用angular时,我们都知道输入框可以通过[(ngModel)]实现数据双向绑定,不可避免更多的会使用到组件之间互相传值,通常通过方括号[]和圆括号()实现组件之间的传值,只是以单向传值的方式会变得尤为繁琐,那么组件之间是不是也可实现像[(ngModel)]一样双向绑定互相传值的方式?
举个栗子~
实现通过点击父组件按钮显示子组件dialog,点击dialog确定按钮,关闭隐藏dialog。
1 // app.component.html 2 <h1>我是父组件</h1>
3 <button (click)="clickBtn()">点击我触发child组件</button>
4 <child [(isShow)]="isShow"></child>
1 // app.component.ts
2 import { Component, OnInit } from '@angular/core'; 3 @Component({ 4 selector: 'app', 5 templateUrl: './app.component.html', 6 styleUrls: ['./app.component.css'] 7 }) 8 export class AppComponent implements OnInit { 9 isShow: boolean = false; 1
11 ngOnInit(){}
13 clickBtn() { 14 this.isShow = true; // 初始化isShow值为true传给子组件 15 } 16
17 }
此时子组件接收到父组件传过来的isShow的值:
1 // child.component.html 2 <div class="dialog_box" *ngIf="isShow">
3 <h1>我是子组件,是否将我关闭?</h1>
4 <p><span (click)="submit()">确定</span></p>
5 </div>
1 import { Component, OnInit, EventEmitter } from '@angular/core'; 2
3 @Component({ 4 selector: 'child', 5 templateUrl: './child.component.html', 6 styleUrls: ['./child.component.css'] 7 }) 8
9 export class ChildComponent { 10 @Input() isShow: Boolean; 11 @Output() isShowChange = new EventEmitter(); 12 14 submit(){ 15 this.isShow = false;
this.isShowChange.emit(this.isShow); 16 } 17 }
以上,就实现了组件之间双向绑定,同时需要注意的地方,输出属性必须在输入属性的基础上加上“change”后缀,这里是不可以随便命名的,比如输入属性的变量名为data,那么传回给父组件接收的输出属性必须为dataChange。