根据具有反应性表单的单选按钮更改表单-Angular 2+

时间:2019-05-21 17:11:24

标签: angular typescript primeng angular-reactive-forms

我有3个单选按钮,当我单击每个按钮时,应该会出现不同的形式。 但是我在反应式表单与表单控件发生冲突时遇到问题

<div class="ui-g-12 ui-md-12 ui-lg-12 ui-fluid espacamento-baixo">
            <div class="ui-g-3"><p-radioButton formControlName="group1" [(ngModel)]="radioForm" value="imagem" label="Imagem" inputId="imagem"></p-radioButton></div>
            <div class="ui-g-3"><p-radioButton formControlName="group1" [(ngModel)]="radioForm" value="video" label="Video" inputId="video"></p-radioButton></div>
            <div class="ui-g-3"><p-radioButton formControlName="group1" [(ngModel)]="radioForm" value="link" label="Link" inputId="link"></p-radioButton></div>
            <div class="ui-g-3"><p-radioButton formControlName="group1" [(ngModel)]="radioForm" value="wistia"label="Wistia" inputId="wistia"></p-radioButton></div>    
        </div>

        <div class="ui-g-6 ui-md-6 ui-lg-6 ui-fluid espacamento-baixo">
            <div *ngIf="radioForm == 'wistia'" >
                <p> aqui seu formulario para {{ radioForm }}</p>
            </div>
        </div>

        <div class="ui-g-6 ui-md-6 ui-lg-6 ui-fluid espacamento-baixo">
            <div *ngIf="radioForm == 'imagem'" >
                <p> aqui seu formulario para {{ radioForm }}</p>
            </div>
        </div>

        <div class="ui-g-6 ui-md-6 ui-lg-6 ui-fluid espacamento-baixo">
            <div *ngIf="radioForm == 'link'">
                <p> aqui seu formulario para {{ radioForm }}</p>
            </div>
        </div>

        <div class="ui-g-6 ui-md-6 ui-lg-6 ui-fluid espacamento-baixo">
            <div *ngIf="radioForm == 'video'">
                <p> aqui seu formulario para {{ radioForm }}</p>
            </div>
        </div>

我测试了这两种模式以进行验证,但没有成功

ngOnInit() {
    //passando um objeto javascript
    this.formConteudo = this.formBuilder.group({
      titulo: ['', Validators.required],
      modalidade: ['', Validators.required],
      descricao: ['', Validators.required],
      id: ['', Validators.required],
      nivel: ['', Validators.required]  
    });

this.formConteudo = new FormGroup({
       titulo: new FormControl({ value: '' }, Validators.compose([Validators.required])),
       modalidade: new FormControl({ value: '' }, Validators.compose([Validators.required])),
       descricao: new FormControl({ value: '' }, Validators.compose([Validators.required])),
       id: new FormControl({ value: '' }, Validators.compose([Validators.required])),
       nivel: new FormControl({ value: '' }, Validators.compose([Validators.required]))
     });

1 个答案:

答案 0 :(得分:1)

formControlName是ReactiveFormsModule的FormGroup部分的子级,而ngModel是FormsModule的一部分。您尚未声明模板中存在formControlName的FormGroup。

如果要跟踪select的值,则不需要特定的FormGroup,只需绑定select的值即可。

我简化了一点逻辑,并创建了一个Stackblitz演示 https://stackblitz.com/edit/angular-smu83a

我正在获取select的值并显示相应的表单。

要了解更多信息,请阅读具有和示例的官方文档 https://angular.io/guide/forms-overview