angular - ngOninit 仅运行一次 - 表单未更新
问题描述
我有带有材质导航列表的材质 sidenav 容器:
<mat-sidenav-container class="cont">
<mat-sidenav #drawer mode="side" opened role="navigation">
<mat-nav-list>
<table>
<tr *ngFor = "let thing of values">
<td>
<button [class.selected]="thing === selectedThing" (click) = "onSelectedThing(thing)">{{thing.Date}}</button>
</td>
</tr>
</table>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<app-thing [thing] = "selectedThing"></app-thing>
</mat-sidenav-content>
</mat-sidenav-container>
当我单击按钮时,我将发送到应查看的应用程序组件元素。
在组件中,我有:
<div>
<app-add-costs [thingIDCost]="thing.thingId"
[Date1] = "thing.Date1"
[Date2] = "thing.Date2">
</app-add-costs>
</div>
所以我有另一个组件,我发送表单中公开的参数。app-add-costs 组件如下所示:
export class AddCostsComponent implements OnInit {
@Input() thingIDCost: number;
@Input() Date1: string;
@Input() Date2: string;
myForm: FormGroup;
constructor(private srv: HttpserviceService, private router: Router, private location: Location, private fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this.fb.group({
Date1: [this.Date1, [Validators.required]],
Date2: [this.Date2, [Validators.required]]
}, {
validator: this.validateDates
}
),
}
}
在 HMTL 中,我只是以以下形式筛选它:
<form [formGroup]="myForm" (submit)="sendDates()">
<table align="right">
<tr>
<td>
Date1
</td >
<td>
<mat-form-field>
<input matInput type="datetime-local" formControlName="Date1">
</mat-form-field>
</td>
</tr>
<tr>
<td>
Date2
</td>
<td>
<mat-form-field>
<input matInput type="datetime-local" formControlName="Date2">
</mat-form-field>
</td>
</tr>
</table>
</form>
问题是当我单击导航列表时,值 Date1 和 Date2 没有改变。他们一直持有第一个值(来自列表中的第一个元素)。
我还注意到在控制台中我看到 OnInit 只运行一次。
在列表中移动时如何显示值?
解决方案
用 ngOnChanges 替换 ngOnInit 以便在输入更改时触发。
export class AddCostsComponent implements OnChanges{
@Input() thingIDCost: number;
@Input() Date1: string;
@Input() Date2: string;
myForm: FormGroup;
constructor(private srv: HttpserviceService, private router: Router, private location: Location, private fb: FormBuilder) {
}
ngOnChanges() {
this.myForm = this.fb.group({
Date1: [this.Date1, [Validators.required]],
Date2: [this.Date2, [Validators.required]]
}, {
validator: this.validateDates
}
),
}
}
推荐阅读
- java - 较新的 PDFBox 版本加载 PDF 缓慢
- php - 如何使用具有相同键但多个值的http post将数据发送到php文件api?
- php - 在一行中显示与相同ID相关的数据php laravel
- html - CSS背景图像不显示
- scala - HDFS 文件拆分命令:使用 spark-submit 的 Spark/Scala
- javascript - 使用javascript将html表格转换为csv时如何合并或组合单元格
- c# - 如何防止使用 ListBox 中的箭头在项目之间切换?
- javascript - 使反应组件可点击
- qt - Qt:如何删除白线?
- mysql - MySQL BETWEEN 查询不使用索引