通过抓取ElementRef来禁用按钮:angular2

编程入门 行业动态 更新时间:2024-10-22 17:23:00
本文介绍了通过抓取ElementRef来禁用按钮:angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在单击按钮时禁用它.通过单击,我正在调用一个函数,并且我想使用该函数禁用该按钮.如何使用ElementRef访问按钮的属性并将其禁用?我对如何使用ElementRef不太熟悉. 任何帮助将不胜感激!

I'm trying to disable a button when it is clicked. By clicking I'm calling a function and I want to disable the button using that function. How can I access button's property with ElementRef and disable it? I'm not very familiar with how to use ElementRef. Any help would be greatly appreciated!

推荐答案

如果您确实想通过ElementRef禁用按钮,则可以使用 ViewChild 方法以获取对按钮的引用,然后使用其nativeElement属性将其设置为禁用.

If you really wanted to disable the button via an ElementRef, you can use the ViewChild method to get a reference to your button and then set the button to disabled using its nativeElement property.

import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>My First Angular 2 App</h1> <button #myButton (click)="onClicked()">Click me!</button>` }) export class AppComponent { @ViewChild('myButton') button; onClicked() { this.button.nativeElement.disabled = true; } }

但是, Angular2建议使用ElementRef作为最后的手段.您可以通过属性绑定来实现所需的功能.

However, Angular2 recommends using ElementRef's as a last resort. The same functionality you desire can be achieved through property binding.

import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>My First Angular 2 App</h1> <button [disabled]="isDisabled" (click)="onClicked()">Click me!</button>` }) export class AppComponent { private isDisabled = false; onClicked() { this.isDisabled = true; } }

更多推荐

通过抓取ElementRef来禁用按钮:angular2

本文发布于:2023-11-23 04:53:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620161.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   ElementRef

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!