我遇到的問題是,在嘗試通過 ID 訪問 html 元素時出現(xiàn)以下錯誤。當(dāng)用戶單擊按鈕以將不同的樣式類應(yīng)用于元素時,我試圖訪問 classList。類列表和元素通常始終為空,除非我將 viewEncapsulation 切換回默認(rèn)的模擬設(shè)置。錯誤信息:TypeError: Cannot read property 'classList' of null問題:我試圖讓這個特定組件不繼承我通過 angular.json 文件導(dǎo)入到項(xiàng)目中的第 3 方 SCSS 文件。當(dāng)我使用默認(rèn)的 ViewEncapsulation.Emulated 時,該組件正在繼承與某些組件樣式相沖突的全局 SCSS 樣式。文件結(jié)構(gòu)正常,我把SCSS和HTML放在對應(yīng)的文件中,然后導(dǎo)入到組件中。我覺得這應(yīng)該是大型項(xiàng)目的一個共同主題。如果有不同的方式來切換事件元素的樣式,請告訴我。組件.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>
Angular - 如何在使用 ViewEncapsulation.Native 時訪問
楊__羊羊
2021-06-01 05:13:51