Angular 如何从父级设置角度自定义输入组件(控制值访问器)的值?
我们能够为本地输入元素(如复选框、文本输入等)设置值(如果需要) 它将是这样的:Angular 如何从父级设置角度自定义输入组件(控制值访问器)的值?,angular,Angular,我们能够为本地输入元素(如复选框、文本输入等)设置值(如果需要) 它将是这样的: <input type="text" [value]="customValue"> 以下来自父组件: @Component({ selector: 'child-custom-input', templateUrl: './child-custom-input.component.html', styleUrls: [], providers: [ { provi
<input type="text" [value]="customValue">
以下来自父组件:
@Component({
selector: 'child-custom-input',
templateUrl: './child-custom-input.component.html',
styleUrls: [],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ChildCustomInputComponent),
multi: true,
},
],
})
export class ChildCustomInputComponent implements ControlValueAccessor {
_value: boolean;
onChanged: any = () => {};
onTouched: any = () => {};
constructor() {}
writeValue(value: any) {
this._value = value;
}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setValue(value) {
this._value = value;
this.onChanged(value);
this.check.emit(value);
}
// parent-component.html
<child-custom-input [value]="customInputValue"> </child-custom-input>
//parent-component.html
我怎样才能达到这样的结果呢
类似于将父组件的默认值/初始值设置为自定义子输入组件
// child-custom-input.component.html
<input type="text" placeholder="Input something..." (input)="setValue($event.target.value)">
// child-custom-input.component.html
<input type="checkbox" (input)="setValue($event.target.checked)">
//child-custom-input.component.html
或者可以是一个复选框。唯一需要做的就是将父组件的值设置为这个自定义子输入组件
// child-custom-input.component.html
<input type="text" placeholder="Input something..." (input)="setValue($event.target.value)">
// child-custom-input.component.html
<input type="checkbox" (input)="setValue($event.target.checked)">
//child-custom-input.component.html
为此,您还需要在ChildCustomInputComponent中定义一个@Input()值:any
属性和适当的getter和setter
export class ChildCustomInputComponent implements ControlValueAccessor {
.
.
.
//The internal data model
private innerValue: any = '';
//get accessor
@Input()
get value(): any {
return this.innerValue;
}
//set accessor including call the onchange callback
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
}
这样,您就可以使用ChildCustomInputComponent并从任何父组件定义其value属性,如下所示:
<custom-input name="myCustomComponent" [value]="'Any value here'"></custom-input>
如需进一步澄清,请查看以下工作示例:
能否共享子自定义输入html代码?它将是简单输入元素的模板。使用输入法设置值($event.target.value)。不用担心。您是否尝试过输入属性绑定来设置子组件值?事实是,真正的输入元素位于自定义子组件内。我想要实现的是,我想要从父组件设置这个自定义子组件的输入值,这样真正的输入元素(自定义子组件内部)将接收该值。我尝试过通过输入绑定进行设置,但我认为这不是正确的方法。如果我们能做到这一点就更好了。如果你能提出一些建议,那就太好了。!把你的建议寄给我。如果你能写一些代码就好了。