代码之家  ›  专栏  ›  技术社区  ›  Ben5

服务器端总是接触FormControl

  •  0
  • Ben5  · 技术社区  · 1 年前

    在使用Angular Universal(SSR)时,我注意到我的反应形式有一种奇怪的行为。 当表单控件与“mat radio group”一起使用时,在服务器上呈现时,它将始终处于“touch”状态。当我只想显示实际触摸过的表单控件的验证消息时,这将导致在最初加载页面时验证消息短暂闪烁。

    所以我有一个简单的组件:

    @Component({
      selector: 'page',
      templateUrl: './page.component.html',
      styleUrls: ['./page.component.scss']
    })
    export class PageComponent extends BaseComponent {
      protected formGroup = new FormGroup({
        productKey: new FormControl<string | null>(null, Validators.required)
      });
    
      constructor() {
        super();
      }
    }
    

    当我使用这个标记时,服务器端的表单控件不会被触及:

    <form [formGroup]="formGroup">
      <mat-form-field>
        <mat-label>product</mat-label>
        <input matInput type="text" formControlName="productKey" />
      </mat-form-field>
      {{ formGroup.controls.productKey.touched }}
    </form>
    

    但一旦我只在服务器端使用“mat无线电组”,它就会被状态触动:

    <form [formGroup]="formGroup">
      <mat-radio-group formControlName="productKey">
        <mat-radio-button value="'A'">1</mat-radio-button>
      </mat-radio-group>
      {{ formGroup.controls.productKey.touched }}
    </form>
    

    有人知道这是一个错误还是设计错误,以及如何解决吗?目前,我只能考虑添加一个条件来显示验证消息,当它在浏览器中呈现时,这是真的,但这并不理想。

    0 回复  |  直到 1 年前