不确定这是您要的内容,但是为了在自定义组件中使用formControlName,这是您要做的
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { InputTextComponent } from './input-text';
@NgModule({
declarations: [
AppComponent,InputTextComponent
],imports: [
FormsModule,ReactiveFormsModule,BrowserModule,],bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<form [formGroup]="details">
<input-text formControlName="name"></input-text>
<!-- This should show the name as you change it in your custom control -->
{{details.value | json}}
</form>
app.component.ts
import { Component } from '@angular/core';
import { FormGroup,FormControl } from '@angular/forms';
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})
export class AppComponent {
public details: FormGroup;
constructor(
) {
this.details = new FormGroup({
name: new FormControl("name")
});
}
}
input-text.component.html
<input kendoTextBox [(ngModel)]="value" (ngModelChange)="onChange($event)" />
input-text.component.ts
import { Component,forwardRef } from "@angular/core";
import { NG_VALUE_ACCESSOR,ControlValueAccessor } from "@angular/forms";
@Component({
selector: "input-text",templateUrl: "./input-text.html",styleUrls: ["./input-text.scss"],providers: [
{
provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => InputTextComponent),multi: true
}
]
})
export class InputTextComponent implements ControlValueAccessor {
public value: string;
propagateChange = (value: string) => {};
writeValue(obj: any): void {
this.value = obj;
}
registerOnTouched(fn: any): void {}
registerOnChange(fn) {
this.propagateChange = fn;
}
onChange(newValue){
this.propagateChange(newValue);
}
}
本文链接:https://www.f2er.com/3161504.html