要将父组件绑定到子组件,可以使用Angular模板驱动表单的方式来实现。下面是一个示例代码:
父组件的模板:
父组件的代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentValue: string;
}
子组件的模板:
子组件的代码:
import { Component, Input } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() parentForm: NgForm;
childValue: string;
}
在这个示例中,父组件中的输入框使用[(ngModel)]
来绑定parentValue
属性。然后,将父组件的表单引用#parentForm
传递给子组件,子组件中的输入框使用[(ngModel)]
绑定childValue
属性,并且使用[ngModelOptions]="{ standalone: true }"
来将子组件的输入框设置为独立的表单控件。
通过这样的设置,父组件的表单控件和子组件的表单控件可以共享数据。