繁体   English   中英

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

[英]How to use Angular template reference variable of input to bind particular button which have the same format

现在,我正在尝试按照 Mr. ruth 的示例,从用于打开图像的按钮行中找到将输入与按钮绑定的方法。 但是,我的 web 应用程序中的按钮行具有与以下相同的格式:topnav.component.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.component.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 class 中按钮的项目值,我想将按钮的 onclick 事件绑定到 Angular 模板引用变量的 click() function [(click)="inputFile.click()"]:

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

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

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

然而,文章*ngIf and *ngFor on same element causing error迫使我三思而后行。 你说使用 HTML 元素的 ID 会更好,但我想知道如何为 Angular 检测 HTML 元素的 ID。请给我一个建议。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM