Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.2K
Views
Establecer el valor de <mat-select> programáticamente

Estoy tratando de establecer el valor de 2 campos <input matInput> y <mat-select> programáticamente. Para la entrada de texto, todo funciona como se esperaba, sin embargo, para <mat-select> en la vista, este campo es como si tuviera un valor null . Pero si llamara a console.log(productForm.controls['category'].value , imprime el valor correcto que configuré mediante programación. ¿Me estoy perdiendo algo?

Aquí está el código:

configuración de formulario:

 productForm = new FormGroup({ name: new FormControl('', [ Validators.required ]), category: new FormControl('', [ Validators.required ]), });

fijando el valor:

 ngOnInit() { this.productForm.controls['name'].setValue(this.product.name); this.productForm.controls['category'].setValue(this.product.category); }

html:

 <mat-form-field> <mat-select [formControlName]="'category'" [errorStateMatcher]="errorStateMatcher"> <mat-option *ngFor="let category of categories" [value]="category"> {{category.name}} </mat-option> </mat-select> </mat-form-field>
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

El mat-select angular compara por referencia entre ese objeto y todos los objetos disponibles en el mat-select . Como resultado, no puede seleccionar los elementos que configuró en el campo de categoría. En consecuencia, debe implementar la función de comparación para comparar cualquiera de los atributos de los elementos de la lista como desee, y luego pasar esta función al atributo [compareWith] de mat-select .
Para concluir, aquí hay una instantánea del marcado final y el guión:

 <mat-form-field> <mat-select [formControlName]="category" [compareWith]="compareCategoryObjects"> <mat-option *ngFor="let category of categories" [value]="category"> {{category.name}} </mat-option> </mat-select> </mat-form-field>

Y en la clase de componentes:

 compareCategoryObjects(object1: any, object2: any) { return object1 && object2 && object1.id == object2.id; }

Ahora seleccionará el elemento, o los elementos si se seleccionan varias veces, que configuró para el campo.

Referencia:
https://github.com/angular/material2/issues/10214

Muestra de trabajo:
https://stackblitz.com/edit/angular-material2-issue-t8rp7j

over 4 years ago · Santiago Trujillo Report

0

Se resolvió este problema cambiando el valor de <mat-option> del objeto de category a su id.

 <mat-form-field> <mat-select [formControlName]="'category'" [errorStateMatcher]="errorStateMatcher"> <mat-option *ngFor="let category of categories" [value]="category.id"> {{category.name}} </mat-option> </mat-select> </mat-form-field>

y valor de configuración:

 this.productForm.controls['category'].setValue(this.product.category.id);
over 4 years ago · Santiago Trujillo Report

0

La forma en que puede lograr esto usando objetos es cambiar el marcado de esta manera:

 <mat-select [formControlName]="'category'" [errorStateMatcher]="errorStateMatcher" [compareWith]="compareFn"> <mat-option *ngFor="let category of categories" [value]="category"> {{category.name}} </mat-option> </mat-select>

Luego en componente

 compareFn(x: Category, y: Category): boolean { return x && y ? x.id === y.id : x === y; }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!