Home > Back-end >  How create dynamic form with angular and Mat-select option
How create dynamic form with angular and Mat-select option

Time:08-09

I have an Angular app, and I'm trying to make a dynamic form with Mat-select for the type, and I want to add or remove a field depending on the chosen type.

i so want on this field show if type is null or O.

In future i want more controle on input.

And is ngif not going to generate an error for me because it does not exist.

 <form [formGroup]="form" (ngSubmit)="submit()">
        
        <div *ngIf="typeB" >
            <mat-label>Type B</mat-label>
            <mat-select id="typeb">
              <mat-option *ngFor="let type of typeB" [value]="type.value">
                {{type.viewValue}}
              </mat-option>
            </mat-select>
        </div>
        
<div *ngIf="f['typeb'] == null || f['typeb'].value == 'O'" >
            <label for="idStr">identifiant</label>
            <input
                formControlName="idStr"
                id="idStr"
                type="text"
                >
            </div>
        </div>
...
@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.scss']
})
export class CreateComponent implements OnInit {

  form!: FormGroup;
  typeB = [
    { value: 'A', viewValue: 'APP'},
    { value: 'O', viewValue: 'ORG' },
    { value: 'P', viewValue: 'PER' },
  ];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
  ) { }

  
  ngOnInit(): void {
    this.form = new FormGroup({
      typeb: new FormControl(null, [Validators.required]),
      idStr: new FormControl('', [Validators.required]),
      ...
    });
      },
      error: (e) => {
        alert(e.status   " - "   e.error.message);
      }
    });
  }

  get f() {
    return this.form.controls;
  }

with this code the field is always invisible

If add console.log on function f , I see in the console it's typeb it's always null

CodePudding user response:

Not sure, but typeB is not declared.

So the select is not showing.

CodePudding user response:

Try tro change that *ngIf="f['typeb'] == null || f['typeb'].value == 'O'" by

*ngIf="f['typeb'].value == null || f['typeb'].value == 'O'"

CodePudding user response:

I sorry i'm forgot formControlName

  • Related