Angular - 如何在使用 ViewEncapsulation.Native 时访问

我遇到的问题是,在尝试通过 ID 访问 html 元素时出现以下错误。当用户单击按钮以将不同的样式类应用于元素时,我试图访问 classList。类列表和元素通常始终为空,除非我将 viewEncapsulation 切换回默认的模拟设置。


错误信息:


TypeError: Cannot read property 'classList' of null

问题:我试图让这个特定组件不继承我通过 angular.json 文件导入到项目中的第 3 方 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>


杨__羊羊
浏览 155回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript