在Angular中,可以通过自定义指令来改变元素的输入。以下是一个示例:
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appChangeInput]'
})
export class ChangeInputDirective {
constructor(private elementRef: ElementRef) { }
@Input('appChangeInput') inputValue: string;
ngOnInit() {
this.elementRef.nativeElement.value = this.inputValue;
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
inputValue: string = '默认值';
changeInput() {
this.inputValue = '新的输入值';
}
}
在上述示例中,ChangeInputDirective
是一个自定义指令,它接收一个名为inputValue
的输入属性。在指令的ngOnInit
方法中,通过ElementRef
来获取元素引用,并将其值设置为inputValue
的值。
在ExampleComponent
组件中,我们使用[appChangeInput]
指令绑定了一个名为inputValue
的属性。当点击按钮时,changeInput
方法会改变inputValue
的值,从而改变输入框的内容。
上一篇:Angular指令改变颜色