亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular - 如何在使用ViewEncapsulation.Native時訪問html元素

Angular - 如何在使用ViewEncapsulation.Native時訪問html元素

慕絲7291255 2019-04-12 14:15:17
我遇到的問題是,當我嘗試通過ID訪問html元素時,我遇到以下錯誤。當用戶單擊按鈕以將不同的樣式類應用于元素時,我正在嘗試訪問classList。除非我將viewEncapsulation切換回默認的模擬設置,否則類列表和元素通常都是null。錯誤消息:TypeError: Cannot read property 'classList' of null問題:我試圖讓這個特定的組件不繼承我通過angular.json文件導入到項目中的第三方SCSS文件。當我使用默認的ViewEncapsulation.Emulated時,該組件繼承了與某些組件樣式沖突的全局SCSS樣式。文件結構是正常的,我將SCSS和HTML放在相應的文件中,然后將它們導入到組件中。我覺得這應該是一個與大型項目相關的共同主題。如果有不同的方法來切換事件元素的樣式,請告訴我。組件.ts:import { Component, ViewEncapsulation, OnInit } from '@angular/core';@Component({   encapsulation: ViewEncapsulation.Native,   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.scss']})export class AppComponent implements OnInit {   title = 'scssTesting';   constructor() { }   step: string = 'step1';   step1: any;   step2: any;   step3: any;   ngOnInit() {   }   next() {     this.step1 = document.getElementById('step1');     this.step2 = document.getElementById('step2');     this.step3 = document.getElementById('step3');     if (this.step === 'step1') {       this.step = 'step2';       this.step1.classList.remove("is-active");       this.step1.classList.add("is-complete");       this.step2.classList.add("is-active");     } else if (this.step === 'step2') {         ....   }}組件.scss.progress {   position: relative;   display: flex;   .........}組件.html<div class="container">     <div class="progress">         <div class="progress-track"></div>         <div id="step1" class="progress-step">             Step One         </div>         <div id="step2" class="progress-step">             Step Two         </div>         <div id="step3" class="progress-step">             Step Three         </div>     </div>     <button (click)="next()">Next Step</button></div>
查看完整描述

2 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

我能想到訪問HTML元素的最簡單方法是使用Angulars ElementRef。你可以在這里閱讀更多相關內容。請謹慎使用!下面是一個如何在您的案例中使用它的示例:

在你的 app.component.html

<div #myelement>This is Pink</div>

在你的 app.component.ts

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']})export class AppComponent implements AfterViewInit {
  @ViewChild('myelement') el: ElementRef;
  ngAfterViewInit() {
    this.el.nativeElement.classList.add("myclass");
  }}

在你的 app.component.css

.myclass {
    color: pink;
    font-weight: bold;}

我希望有所幫助!


查看完整回答
反對 回復 2019-05-17
  • 2 回答
  • 0 關注
  • 560 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號