在Angular v3以上版本中,怎么获取 HTML 元素的属性值?

在Angular 中,怎么获取 HTML 元素的属性值?或者说类似js来操作操作html元素的属性

1: 使用 ElementRef
使用 ElementRef 可以直接访问 DOM 元素,并获取其属性值。
父组件 (ParentComponent)

复制代码
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <div #myDiv [attr.data-id]="dataId">Hello, World!</div>
    <button (click)="logDataId()">Log Data ID</button>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  dataId = '12345';

  @ViewChild('myDiv', { static: true }) myDiv: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  logDataId() {
    const dataId = this.myDiv.nativeElement.getAttribute('data-id');
    console.log('Data ID:', dataId);
  }
}
复制代码

2:使用 Renderer2 可以更安全地操作 DOM 元素及其属性。

示例代码
父组件 (ParentComponent)

复制代码
import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <div #myDiv [attr.data-id]="dataId">Hello, World!</div>
    <button (click)="logDataId()">Log Data ID</button>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  dataId = '12345';

  @ViewChild('myDiv', { static: true }) myDiv: ElementRef;

  constructor(private renderer: Renderer2) { }

  ngOnInit(): void {
  }

  logDataId() {
    const dataId = this.renderer.getAttribute(this.myDiv.nativeElement, 'data-id');
    console.log('Data ID:', dataId);
  }
}
复制代码

3:如果你需要获取表单控件的值,可以使用 NgModel 或者表单控件。

示例代码
父组件 (ParentComponent)

复制代码
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <input type="text" [(ngModel)]="inputValue" name="inputValue" id="inputValue">
    <button (click)="logInputValue()">Log Input Value</button>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  inputValue = '';

  constructor() { }

  ngOnInit(): void {
  }

  logInputValue() {
    console.log('Input Value:', this.inputValue);
  }
}
复制代码

4: 使用 ViewChild 和自定义指令
你还可以使用自定义指令来获取 HTML 元素的属性值。

自定义指令 (CustomDirective)

复制代码
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[customAttr]'
})
export class CustomDirective {

  @Input('customAttr') customAttrValue: string;

  constructor(private el: ElementRef) { }

  ngOnChanges() {
    if (this.customAttrValue) {
      this.el.nativeElement.setAttribute('data-custom', this.customAttrValue);
    }
  }
}

父组件 (ParentComponent)
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <div #myDiv customAttr="customValue">Hello, World!</div>
    <button (click)="logCustomValue()">Log Custom Value</button>
  `,
  styleUrls: ['./parent.component.css'],
  imports: [CustomDirective],
  standalone: true
})
export class ParentComponent implements OnInit {

  @ViewChild('myDiv', { static: true }) myDiv: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  logCustomValue() {
    const customValue = this.myDiv.nativeElement.getAttribute('data-custom');
    console.log('Custom Value:', customValue);
  }
}
复制代码

 

@ViewChild("pdfContainer",{static:true}) mytagvalue!:ElementRef;  例如:要求限制类型 mytagvalue!:ElementRef;   
myTagValue!: ElementRef; 表示你确信 myTagValue 在运行时不会是 null 或 undefined
 
编译时:编译器会忽略 myTagValue 可能为 null 或 undefined 的警告。
运行时:如果 myTagValue 实际上是 null 或 undefined,运行时仍然会抛出错误。因此,在使用 ! 之前,最好确保 myTagValue 一定会被正确赋值
谨慎使用:虽然 ! 可以消除编译器的警告,但在实际运行时仍然需要确保变量或属性不会是 null 或 undefined 的要求哦
 
posted @   天天向上518  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2021-09-02 AbpVnext使用分布式IDistributedCache Redis缓存(自定义扩展方法)
2019-09-02 SQlserver高效分页,还在使用row_number(),top之类的?
2019-09-02 EFCore的CodeFirst以及DBFirs的简单使用
2019-09-02 Core3.0的 安装与坑坑坑!!!
点击右上角即可分享
微信分享提示