在Angular中为自定义组件应用双向绑定,可以通过使用ngModel
指令来实现。以下是一个示例代码:
首先,在自定义组件的模板文件中,添加一个input
元素,并使用ngModel
来绑定一个属性和事件:
custom-component.component.html:
然后,在自定义组件的类文件中,定义一个value
属性和一个onChange
方法:
custom-component.component.ts:
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-custom-component',
templateUrl: './custom-component.component.html',
styleUrls: ['./custom-component.component.css']
})
export class CustomComponentComponent {
@Input() value: string;
@Output() valueChange: EventEmitter = new EventEmitter();
onChange(newValue: string) {
this.value = newValue;
this.valueChange.emit(newValue);
}
}
现在,你可以在其他组件中使用这个自定义组件,并进行双向绑定:
app.component.html:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myValue: string = 'Hello Angular';
}
在这个示例中,myValue
是父组件中的一个属性,它被绑定到了自定义组件中的value
属性上。当用户在自定义组件中的输入框中输入内容时,双向绑定会同步更新myValue
的值。