如何使用输入的Angular模板引用变量来绑定具有相同格式的特定按钮



现在,我正试图以鲁斯先生为例,找到将输入与打开图像的按钮行中的按钮绑定的方法。但是,我的web应用程序中的按钮行具有与以下相同的格式:topnav.com.ponent.html:

<button
mat-button
*ngFor="let item of toolNavItems"
(click)='onTopNavClick(item)'
[class.active]="item.selected"
[title]="item.title"
>
<mat-icon [class]="item.icon">{{item.icon}}</mat-icon>

</button>

topnav.com组件.ts:

export class TopnavComponent implements OnInit {
@Output() topnavSelect: EventEmitter<ToolNavItem> = new EventEmitter();
toolNavItems: ToolNavItem[];
constructor(
private sketchService: SketchService,
) { }
ngOnInit(): void {
this.sketchService.menusObs.pipe(untilDestroyed(this)).subscribe(menus => {
this.toolNavItems = menus;
});
}
onTopNavClick(selectedTopnavItem: ToolNavItem) {
this.topnavSelect.emit(this.sketchService.selectMenu(selectedTopnavItem));
}
}

打开图像进行显示的隐藏输入将类似于以下内容:

<input #inputFile class="ng-hide" style="display:none;" name="file" multiple type="file" accept=".jpg, .png, .jpeg, .JPG, .PNG, .JPEG" (change)="getFiles($event)"/>

如何根据item或item.title的值将输入绑定到特定按钮,这是将按钮行与所选按钮分隔开的唯一方法?

下面是sketchService类中按钮的项值,我想将按钮的onclick事件绑定到Angular模板引用变量[(click(="inputFile.click(("]的click((函数:

{
id: 'upload_image',
title: 'Upload Image for Blending',
icon: 'image',
type: 'passive'
}

请告诉我怎么做。最初,我考虑使用*ngIf来检测item.id的值,作为根据以下psudocode为按钮的onclick事件分配适当功能的方法:

*ngIf item.id is 'upload_image'
(click)="inputFile.click()"
else 
(click)="onTopNavClick(item)"

然而,关于同一元素的文章*ngIf和*ngFor导致了错误,这让我不得不三思而后行。您已经说过使用HTML元素的ID将是更好的选择,但我想知道如何检测Angular的HTML元素ID。请给我一个建议。

您已经将整个item对象传递给onTopNavClick事件。根据您的html,项目对象应该包含标题和任何其他有助于识别项目的数据。

然后,您将整个item转发到sketchService,因此sketchService已经知道,并且可以使用您提到的任何属性。

我不会依赖标题,因为这似乎是一个UI问题,而不是要采取的操作的标识符。如果可以,可以使用更稳定的标识符向ToolNavItem添加另一个属性,如eventId

最新更新