currently uses ng6 to customize a form control, app-popup-search
, but when used in the form
form, it is unable to get its corresponding value, please take a look at it, thank you.
Custom form control code:
import { FormGroup,FormBuilder,NG_VALUE_ACCESSOR } from "@angular/forms";
import { ControlValueAccessor } from "@angular/forms";
import { Component, OnInit,Inject,forwardRef,ChangeDetectionStrategy } from "@angular/core";
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA} from "@angular/material";
import { ConfirmDialogComponent} from "../confirm-dialog";
@Component({
selector: "app-popup-search",
template: `
<form [formGroup]="form">
<div class="input-group">
<input type="text" formControlName="testName" (change)="on1Change()" class="form-control" placeholder="hello worlds">
<span class="input-group-addon pointer" mat-raised-button (click)="openSearchDialog()"></span>
</div>
</form>
`,
styles: [`
`],
providers:[
ConfirmDialogComponent,
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => PopupSearchComponent),
multi: true,
},
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PopupSearchComponent implements ControlValueAccessor,OnInit {
private propagateChange = (_: any) => {};
names:string;
form:FormGroup;
selectedData:string;
constructor(public dialog:MatDialog,
private fb:FormBuilder
) { }
ngOnInit() {
this.form=this.fb.group({
testName:[]
});
}
openSearchDialog():void{
const dialogRef=this.dialog.open(ConfirmDialogComponent,{
width:"850px",
data:{names:"wangkai"}
});
dialogRef.afterClosed().subscribe(result => {
this.selectedData=result.names;
this.form.get("testName").setValue(result.names,{emitEvent: false, emitModelToViewChange: true, emitViewToModelChange: true});
this.propagateChange(result.names);
console.log(`Dialog result: ${result.names}`); // Pizza!
});
}
public on1Change(){
console.log(this.selectedData);
this.propagateChange(this.selectedData);
}
public writeValue(obj:string){
console.log(obj);
if(obj){
this.form.get("testName").patchValue(obj);
}
}
public registerOnChange(fn:any){
console.log(fn);
this.propagateChange(fn);
}
public registerOnTouched(){
}
}
form form uses code HTML:
<form [formGroup]="formMultiple" (ngSubmit)="aaSubmit()">
<div class="row">
<div class="col-sm-6">
<div class="row">
<div class="col-sm-3">
<label for="">Name</label>
</div>
<div class="col-sm-9">
<app-popup-search ngDefaultControl formControlName="name"></app-popup-search>
</div>
</div>
</div>
</div>
</form>
TS Code:
ngOnInit() {
this.formMultiple=this.fb.group({
"name":[""]
});
}
Please take a look at it, thank you!