簡體   English   中英

在 Angular 6 中重新加載組件的最佳方法

[英]Best way to reload component in Angular 6

在我的應用程序中,我有一個不同“問題”的列表,每個問題指的是由變量QuestionIndex控制的兩個組件之一,該變量基本上采用列表中的當前 object。

所以我有Component A ,其中有一個帶有兩個單選按鈕的表單:

<form [formGroup]="form">
  <label>
    <span class="inlineBlock">
      <input type="radio" value="Ja" formControlName="response" class="radioInput">
      <span class="labelSpan">Ja</span>
    </span>
  </label>
  <label>
    <span class="inlineBlock">
    <input type="radio" value="Nej" formControlName="response" class="radioInput">
    <span class="labelSpan">Nej</span>
    </span>
  </label>

</form>

我填寫表格並增加QuestionIndex

然后該組件內部的表單不會重新加載,而是已經填寫。

如何確保component完全重新加載?

我已經嘗試過使用ngOnChanges但這不會真正起作用,因為我需要重置很多值,並且每次重置都會再次觸發ngOnChanges

它是如何使用的

下面是當索引增加時組件的使用方式, currentQuestion object 被更改,因此component被加載

<app-radio-question [text]="currentQuestion.text"
                    *ngIf="currentQuestion.type == 'RadioQuestion' && !showEndQuestion"
                    [title]="currentQuestion.title" [NoOptionText]="currentQuestion.noOption"
                    [YesOptionText]="currentQuestion.yesOption"
                    [cacheData]="cacheData"
                    (formChangedEvent)="OnQuestionResponse($event)"></app-radio-question>

但是,此組件已更改但未更新,這意味着如果我更改其中的值,則會收到ExpressionChangedAfterItHasBeenCheckedError錯誤。

此輸入根本不綁定到任何變量。 您應該考慮這樣做並重置該特定變量

HTML

    <input [(ngModel)]="inputVariableName" (change)="onChangeFunc()" value="true" formControlName="response" class="radioInput"/>

TS

inputVariableName = false; // initial

onChangeFunc() {
    inputVariableName = false; //set it to initial again
}

但是您必須導入 FormsModule 才能使其正常工作。

我建議您為單選按鈕使用某種框架。 我使用 Angular 材質,單選按鈕分組如下:

<mat-radio-group aria-label="Select an option">
  <mat-radio-button value="1">Option 1</mat-radio-button>
  <mat-radio-button value="2">Option 2</mat-radio-button>
</mat-radio-group>

一個完整的例子可以在這里找到Radio Button Angular Material

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM