【问题标题】:during the initial page load need to change the add/edit color在初始页面加载期间需要更改添加/编辑颜色
【发布时间】:2018-04-02 17:17:47
【问题描述】:
  • 我正在学习 angular2。
  • 在初始页面加载期间,我需要更改添加/编辑首选项颜色。
  • 您能告诉我如何解决吗?
  • 我搜索了加载事件。
  • 但我什么都查不到。
  • 在下面提供我的代码。

https://stackblitz.com/edit/angular-zddcxy?file=app/app.component.html

<!-- language-all: lang-or-tag-here -->

 public loadColor() {
      console.log('this.changeColor--->');
  }
    <span id="open1" (click)="loadColor()">add/edit prefrence</span>

【问题讨论】:

    标签: javascript html css angular kendo-ui


    【解决方案1】:

    使用 ngOnInit 和 ViewChild 装饰器

    @ViewChild('open1') el:ElementRef;

      ngOnInit(): void {
      const span = this.el.nativeElement;
      span.style.color = 'red';
    }
    

    在 HTML 中添加 #open1 作为 ref

    <span #open1 id="open1" (click)="loadColor()">add/edit prefrence</span>
    

    https://stackblitz.com/edit/angular-uvmusm?file=app/app.component.html

    【讨论】:

    • 嘿,谢谢您的回复....你能解释一下,以便将来我自己做....不知道为什么我们使用 viewchild 和原生元素
    • 这只是一种直接访问 DOM 的方式。 ViewChild 它是一个装饰器,可让您操作类中的引用元素。你用 #toto 标识符指向 dom 的一个元素。你用@ViewChild('toto') el:ElementRef 得到它,然后在ngOnInitngAfterViewInit 上你可以在组件加载时操作这个DOM 元素
    【解决方案2】:

    要捕获初始页面加载事件,您需要使用 Angular 组件生命周期挂钩。所以你需要它添加 ngOnInit 由 Angular 调用完成创建组件。

    要添加ngOnInit,您需要导入OnInit

    import {Component, OnInit} from '@angular/core';
    

    需要添加ngOnInit钩子方法

     //implement OnInit's `ngOnInit` method
    ngOnInit(){
       console.log('this.changeColor--->');
    }
    

    欲了解更多信息https://angular.io/guide/lifecycle-hooks

    我已经更新了你的代码https://stackblitz.com/edit/angular-gzqebz?file=app/app.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2013-05-08
      • 2020-09-14
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多