Angular 如何将id属性指定给mat select?

Angular 如何将id属性指定给mat select?,angular,angular-material,Angular,Angular Material,是否可以将id属性添加到mat select 我试过: <mat-select id="mat-select-{{example.id}}"> <mat-option *ngFor="let u of users" [value]="u.id"> {{u.name}} </mat-option> </mat-select> {{u.name} 但是我无法使用文档检索元素。getElementById('mat-

是否可以将
id
属性添加到
mat select

我试过:

<mat-select id="mat-select-{{example.id}}">
    <mat-option *ngFor="let u of users" [value]="u.id">
        {{u.name}}
    </mat-option>
</mat-select>

{{u.name}

但是我无法使用
文档检索元素。getElementById('mat-select-10')
,它返回null。

我不确定我是否清楚地理解了您的需求,但我认为您希望一个唯一的id与mat-select组件中的下拉值相关联。如果这是正确的,这就是你可以遵循的stackblitz

为了给您一个概览,在mat选项中,您需要如下设置id属性:

<mat-select>
    <mat-option *ngFor="let food of foods" [value]="food.value" [id]="food.value">
       {{food.viewValue}}
   </mat-option>
</mat-select>

{{food.viewValue}

如果检查元素,您将发现与DOM元素关联的动态。希望有帮助。

为什么要检索元素?在呈现视图之前,您可能正在调用
document.getElementById
?例如,在组件的构造函数中?您还应该检查DOM,并查看该
mat select
isTo的ID值,以检索/设置值。我动态创建了几个,但找不到其他方法来检索或设置所选的值。是否检查了角度形式?我想为每个
mat select
设置唯一的id,而不是使用下拉列表值。