首页 > 其他分享 >在Angular v3以上版本中,怎么获取 HTML 元素的属性值?

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

时间:2024-09-02 17:35:57浏览次数:6  
标签:ElementRef parent ParentComponent v3 Angular ViewChild HTML OnInit myDiv

在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 的要求哦  

标签:ElementRef,parent,ParentComponent,v3,Angular,ViewChild,HTML,OnInit,myDiv
From: https://www.cnblogs.com/Fengge518/p/18393151

相关文章

  • [vue] jszip html-docx-js file-saver 图片,纯文本 ,打包压缩,下载跨域问题
    npminstalljszipfile-saverimportJSZipfrom'jszip';importFileSaverfrom'file-saver';JSZip创建JSZip实例:constzip=newJSZip();创建文件:支持导出纯文本zip.file("hello.txt","HelloWorld\n");创建文件夹:zip.folder("file")......
  • H5 Morvin高颜值后台管理模板、html5+bootstrap5后台管理前端模板网站模板
    介绍推荐一个高颜值的应用模板,Morvin是一个基于Bootstrap5实现的后台管理系统模板。基于简单的和模块化的设计,这使得它很容易定制。这套后台模板有大量的可重用的和漂亮的UI元素,小部件等。帮助你的团队移动更快,节约开发成本,可以创建任何网站的后台数据管理,或者WEB应用系统的界......
  • What's new in PikiwiDB(Pika) v3.5.5
    尊敬的社区朋友及PikiwiDB(Pika)用户们:非常高兴地宣布---PikiwiDB(Pika)【下文简称Pika】长期维护版本v3.5的最新版本---v3.5.5今天正式发布。在这个版本中,除了修复所有已知的主从复制bug外,通过引入RTC特性其性能又有了大幅度提升,且主从failover机制兼容了Redis-Se......
  • HTML
    HTML大体框架<!DOCTYPEhtml><htmllang="en">//语言english<head><metacharset="UTF-8">//字符编码<metahttp-equiv="X-UA-Compatible"content="IE=edge">//兼容IE<metaname=&qu......
  • 尝试了一切方法,但HTML内容仍未显示
    如果尝试了一切方法但HTML内容仍未显示,以下是一些可能的解决步骤:检查HTML代码:确保HTML代码没有语法错误或缺失的标签。使用HTML验证工具可以帮助你检查代码的正确性。检查文件路径:确保HTML文件的路径正确,并且文件存在于指定的位置。检查浏览器设置:确保浏览器没有设置为阻......
  • HTML表单
    1.表单组件<span>:文本标签(没作用主要给文本加其他属性)<label>:文本标签(没作用主要给文本加其他属性)<form>:表单标签action提交路径method提交方式(get|post)<button>:按钮标签<select>...<option>:下拉框(下拉列表)selected设置默认值<texarea>:文本域|多行文本框c......
  • HTML表单中input标签中的type属性使用
     type属性表示表单控件的类型一,radio,checkbox,date,time,datetime-local,month,week等    1.radio:单选框             单选中一组内容必须设置同一个name名;                单选中每一个表单控件必须设置value......
  • HTML 基础一
    1.什么是HTML?HTML是HypeTextMark-upLanguage的简称,即超文本标记语言,是用于创建网页的标准标记语言。HTML的全称为:HypeTextMark-upLanguage,指的是超文本标记语言。它不是一种编程语言(如java、C语言等),是一种标记语言,是一套标记标签,用来描述网页。标记:就是标......
  • php htmlspecialchars()、htmlentities()、addslashes() 的区别
    1差别htmlspecialchars()和htmlentities()唯一的差别是对于不认识的编码是否转义。比如,对于西欧编码ISO-8859-1来说,中文字符是“不认识的编码” 2举个例子说明差别2.1转义不认识的编码有差别$str='中文字符';echo"\nhtmlentities会转义:——\n";echohtmlen......
  • Python将HTML转MD
    1.下载hteml2text模块2.代码importosimporthtml2textinput_folder="C:\\Users\\jude\\Desktop\\res\\cnblogs_blog_judes.20240831122513\\judes"#输入文件夹路径output_folder="C:\\Users\\jude\\Desktop\\res\\cnblogs_blog_judes.......