下面是一个示例代码,展示了如何在Angular中实现两个输入的单向镜像:
在组件的HTML模板中,我们可以使用双向数据绑定来实现输入框的值与组件属性的绑定。我们可以通过在输入框的ngModel指令中绑定组件属性,从而实现输入框的值与组件属性的同步。
在组件的TypeScript文件中,我们可以定义两个属性来存储输入框的值,以及一个方法来实现镜像的功能。在ngOnInit生命周期钩子中,我们可以初始化输入框的值。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-mirror',
templateUrl: './mirror.component.html',
styleUrls: ['./mirror.component.css']
})
export class MirrorComponent implements OnInit {
inputValue1: string;
inputValue2: string;
ngOnInit() {
this.inputValue1 = '';
this.inputValue2 = '';
}
mirror() {
this.inputValue2 = this.inputValue1;
}
}
在上述代码中,我们定义了两个输入框的值属性inputValue1
和inputValue2
,以及一个mirror
方法,该方法会将inputValue1
的值赋给inputValue2
。
通过在模板中使用双向数据绑定,当输入框的值改变时,对应的属性值会自动更新;当属性值改变时,输入框的值也会自动更新,从而实现了两个输入框的单向镜像效果。
希望这个例子能对你有所帮助!