首页 > 解决方案 > 将数据从父组件传递到子组件(包含响应式表单)以更新该表单的详细信息

问题描述

粗略设计

我对 Angular 比较陌生,我希望通过反应形式实现上述目标。我想我在组件设计和反应式表单模式之间感到困惑。

问题

  1. 我们第一次加载父组件时,使用 url 参数,它将值传递给子组件,搜索文本框将具有正确的值。如果我在浏览器上单击返回并且父级更新它的 searchTerm,它再次传递给子组件,它永远不会更新搜索文本框,因为 child.ngOnInit() 不会再次执行。

  2. 这甚至是在子组件中声明 formGroup 的有效设计吗?我见过的大多数示例都在父级中声明了一个 formGroup,然后包含一个子组件,该子组件然后有 1 个或多个 formControls....但这并不意味着现在任何其他想要包含我的子组件的组件现在必须声明一个 formGroup,子组件似乎不太独立。

父视图

<searchBox (search)="onSearchTextEntered($event)" [searchText]="this.searchText"></searchBox>

父组件

  ngOnInit() {
     
     /* 
        1) check url params, execute search, set searchText value that is passed to childComponent
        so it can populate searchBox text 
        
        2) Subscribe to NavigateEnd event of router to catch back/fwd browser click, execute search, set searchText value that is passed to childComponent
        so it can populate searchBox text
     */
  }

子视图

<input type="text" [formControl]="searchTerm">

子组件

@Input() searchText: string;
@Output() search: EventEmitter<string> = new EventEmitter();
searchSection = new FormGroup({
    searchTerm: new FormControl()

ngOnInit() {
this.searchSection.get('searchTerm').setValue(this.searchText);
}
...

标签: angularangular-reactive-forms

解决方案


formGroup我在子组件中使用是完全有效的。

    1) check url params, execute search, set searchText value that is passed to childComponent so it can populate searchBox text 

为此,您可能需要subject像这样创建然后订阅模板

<searchBox (search)="onSearchTextEntered($event)" [searchText]="subjectRoutes | async"></searchBox>

在这种情况下,您需要this.searchSection.get('searchTerm').setValue(this.searchText)每次更新

@Input() searchText: string;变化。您可以通过为此属性创建设置器或使用ngOnChanges生命周期方法来实现此目的。

或者,您可以创建自定义可重用formControl 自定义表单控件


推荐阅读