【问题标题】:Angular2 - Get a specific element in the DOM and change it's classAngular2 - 获取 DOM 中的特定元素并更改它的类
【发布时间】:2017-10-13 12:11:34
【问题描述】:

假设我有一个这样的无序列表

<div>
     <ul class="data-container">
            <li #H1>00</li>
            <li #H2>01</li>
            <li #H3>02</li>
            <li #H4>03</li>
            <li #H5>04</li>
            ...
        </ul>
    </div>

使用 ViewChild 根据局部变量获取元素的最佳方法是什么,然后检索它的值并给它一个特殊的类(比如 class="active")

我可以在这里使用过滤器或查找功能吗?

另外,假设我想选择其中一个项目,有没有比在所有项目上都使用(click)="SelectElement()" 更好的方法?

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您可以创建一个 LiDirective 来标记所有 LI。之后,您可以使用我的 QueryList 提供的所有 API,例如 find、filter、reduce、toArray ...

      @Directive({
        selector:'li'
      })
      export class LiDirective{}
    
      @Component({
        selector: 'my-app',
        template: `
          <div>
            <h2>Hello {{name}}</h2>
    
            <div>
           <ul class="data-container">
                  <li>00</li>
                  <li #H2>01</li>
                  <li #H3>02</li>
                  <li #H4>03</li>
                  <li #H5>04</li>
              </ul>
          </div>
          </div>
        `,
      })
      export class App {
        @ViewChildren(LiDirective, {read:ElementRef}) lis: QueryList<any>;
        name:string;
        constructor(private renderer: Renderer2) {
          this.name = `Angular! v${VERSION.full}`
        }
    
        ngAfterViewInit() {
          let second = this.lis.toArray()[2];
          this.renderer.setStyle(second.nativeElement, 'color', 'blue');
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2016-11-16
      • 2017-07-11
      • 2016-07-20
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多