首页 > 解决方案 > 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 只运行一次。

在列表中移动时如何显示值?

标签: angularformsangular-materialngoninit

解决方案


用 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
      }
      ),
  }
}

推荐阅读