angular - 将数据从父组件传递到子组件(包含响应式表单)以更新该表单的详细信息
问题描述
我对 Angular 比较陌生,我希望通过反应形式实现上述目标。我想我在组件设计和反应式表单模式之间感到困惑。
问题
我们第一次加载父组件时,使用 url 参数,它将值传递给子组件,搜索文本框将具有正确的值。如果我在浏览器上单击返回并且父级更新它的 searchTerm,它再次传递给子组件,它永远不会更新搜索文本框,因为 child.ngOnInit() 不会再次执行。
这甚至是在子组件中声明 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);
}
...
解决方案
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
自定义表单控件
推荐阅读
- python - 计数和突出显示问题
- javascript - 在 AJAX 请求之后,如何使用反应上下文 api 值更新 Formik 初始值?
- php - 如何修复 mysqli 更新数据库中的错误值?
- excel - 无法执行简单的 Excel.Application 事件处理
- c - 当我的所有输入都是整数时,为什么使用 float 而不是 int 会给我不同的结果?
- jquery - 只选择元素与jquery相同的div
- java - 如何将 Jena QuerySolution 结果写入 RDF/XML 文件?
- typescript - 承诺解决的数据不可访问
- ruby-on-rails - 使用 capybara 和 docker-chromedriver 时无法连接到 websocket
- ejs - 如何使用 EJS 有条件地显示变量