While working with Antd, I’ve always wondered how the custom component for bidirectional binding works.
Because I used it all the time, I didn’t read the document carefully.
Take time today for a simple wank.
In NG, () is a one-way data flow from the view target to the data source, so [()] is bidirectional binding. In simple terms, it is a syntax sugar given by ng. It helps us to do the event listening of the event emitted by the child component, and then assign the value.
Child component: HTML
<input placeholder="test" type="text" [(ngModel)]="qc" #qq (ngModelChange)="testevent()">
Copy the code
Child components: ts
@Component({ selector: 'app-qingcheng', templateUrl: './qingcheng.component.html', styleUrls: ['./qingcheng.component.less'] }) export class QingchengComponent implements OnInit { @Input() username: string; @Output() usernameChange = new EventEmitter(); constructor() { } ngOnInit() { } testevent() { console.log(this.username); this.usernameChange.emit(this.username); }}Copy the code
When sending external events, make sure xxxChange, the events ending with Change are correct, otherwise they cannot be bidirectional binding.
The pit for half a day to solve: segmentfault.com/a/119000001…
Parent component: HTML
<app-qingcheng #qingcheng [(qc)]="testbind"></app-qingcheng>
{{testbind}}
Copy the code
Parent component: TS
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
title = 'qctest';
testbind = '';
}
Copy the code