Angular2 ElementRef nativeElement检查元素是否被禁用

时间:2016-03-17 10:05:16

标签: javascript angular

我的指令中有这个,名为'bgcolor':

       MySqlConnection conn = new MySqlConnection("datasource=localhost;port = 3306;username = root;password = ");
        MySqlCommand comm = new MySqlCommand("select Fee,Amount from system.other_school_fees ;", conn);

            MySqlDataAdapter ssda = new MySqlDataAdapter();
            ssda.SelectCommand = comm;
            DataTable ddbdataset = new DataTable();
            ssda.Fill(ddbdataset);
            BindingSource bbsource = new BindingSource();

            bbsource.DataSource = ddbdataset;
            dataGridView2.DataSource = bbsource;
            ssda.Update(ddbdataset);
            dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            int d = 0;
            for (int b = 0; b < dataGridView2.Rows.Count; b++)
            {
                d += Convert.ToInt32(dataGridView2.Rows[b].Cells[1].Value);
            }

            lblOSF.Text = d.ToString();

在我的模板中,我有:

export class BgColorDirective {
    constructor(el: ElementRef) {
        console.log(el.nativeElement.disabled); // show "false"
        if (el.nativeElement.disabled) {
            el.nativeElement.style.backgroundColor = '#5789D8';
            el.nativeElement.style.color = '#FFFFFF';
        }
    }

我不明白为什么<button (click)="submitData()" [disabled]="true" bgcolor [routerLink]="['Onboarding']"> </button> 会返回el.nativeElement.disabled

3 个答案:

答案 0 :(得分:4)

我认为你需要等待绑定得到解决。例如,将构造函数的代码移动到ngOnInit钩子:

export class BgColorDirective {
  constructor(private el: ElementRef) {
  }

  ngOnInit() {
    console.log(this.el.nativeElement.disabled); // show "true"
    if (this.el.nativeElement.disabled) {
        this.el.nativeElement.style.backgroundColor = '#5789D8';
        this.el.nativeElement.style.color = '#FFFFFF';
    }
  }
}

来自https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html的提醒:

  

ngOnInit :在Angular初始化数据绑定输入属性后初始化指令/组件。

答案 1 :(得分:4)

请勿直接使用nativeElement,而是使用Renderer

export class BgColorDirective {
    constructor(el: ElementRef, renderer: Renderer) {

        if (yourCondition) {
            renderer.setElementStyle(el.nativeElement, 'background-color', '#5789D8');
            renderer.setElementStyle(el.nativeElement, 'color', '#FFFFFF');
        }
    }
}

答案 2 :(得分:1)

尝试在ngAfterViewInit方法中执行相同操作:

export class BgColorDirective {
    constructor(private el: ElementRef) {}
    ngAfterViewInit():void {
        console.log(this.el.nativeElement.disabled);
        if (this.el.nativeElement.disabled) {
            this.el.nativeElement.style.backgroundColor = '#5789D8';
            this.el.nativeElement.style.color = '#FFFFFF';
        }
    }
}