【发布时间】:2018-08-28 04:23:48
【问题描述】:
我在 Angular 2 项目中使用了 Angular 材质。
我想在 mat-select 的选定值中放置一个静态图像(html 元素)。
但我没有找到解决方案。
有人可以帮我吗?
【问题讨论】:
标签: html angular css angular-material
我在 Angular 2 项目中使用了 Angular 材质。
我想在 mat-select 的选定值中放置一个静态图像(html 元素)。
但我没有找到解决方案。
有人可以帮我吗?
【问题讨论】:
标签: html angular css angular-material
我建议将<span> 放在<mat-select-trigger> 和/或<mat-option> 元素中,然后按照this answer 规定的方式将html 绑定到它。
<mat-select>
<mat-select-trigger>
<span [innerHTML]="myHtmlWithImageTag"></span>
</mat-select-trigger>
<mat-option *ngFor="let item of items" [value]="item">
<span [innerHTML]="myHtmlWithImageTag"></span>
</mat-option>
</mat-select>
【讨论】:
只需在<mat-option> 中添加<img> 标签即可。对于选定的选项,使用ngClass 将图像设置为背景。您必须按选项使用一个类:
HTML
<mat-select [(value)]="selected" [ngClass]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1
<img with="10" height="10" src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg">
</mat-option>
<mat-option value="option2">Option 2
<img with="10" height="10" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg">
</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
CSS:
.option1{
background: url("https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg") center / contain no-repeat;
white-space: nowrap
}
.option2{
background: url("https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg") center / contain no-repeat;
white-space: nowrap;
display:inline
}
【讨论】:
当涉及到这种或类似的情况时,我是这样做的:
<mat-form-field>
<mat-select [(value)]="selectedLanguage">
<mat-select-trigger>
<span class="flag-icon flag-icon-{{ selectedLanguage | lowercase}}"> </span>
</mat-select-trigger>
<mat-option *ngFor="let lang of Languages" [value]="lang">
<span class="flag-icon flag-icon-{{ lang | lowercase}}"></span>
</mat-option>
</mat-select>
</mat-form-field>
当然,<mat-select-trigger> 和 ` 内部标签也可以是任何标签 img,它们可以工作!!
【讨论】:
mat-option 内的所有内容执行“toString()”并将其连接在一起。不幸的是,框架没有简单的方法使用您的mat-option HTML 作为默认触发器,因为它只是可以以各种方式生成的 HTML。
mat-select 中进行双向数据绑定。请改用主题标签#selectedLanguage",例如<mat-select #selectedLanguage>,如果您使用的是formGroup,请使用selectedLanguage.value ;)