Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法从Angular 7中的数据属性中提取数据_Javascript_Angular_Typescript_Angular7_Custom Data Attribute - Fatal编程技术网

Javascript 无法从Angular 7中的数据属性中提取数据

Javascript 无法从Angular 7中的数据属性中提取数据,javascript,angular,typescript,angular7,custom-data-attribute,Javascript,Angular,Typescript,Angular7,Custom Data Attribute,我试图重用kendoDropDownListBox,并通过使用父级中的数据属性来查询正确的数据源,并结合switch case语句来设置数据。代码的switch case部分不包括在内,因为当正确的数据被传递给它时,它就工作了,我只是无法从data属性中提取正确的数据(如果我使用按钮传递数据,它工作得很好) 我尝试了许多方法来提取属性,包括以下内容 element.dataset[关键字名称] element.getAttribute('keyname'] 如果我执行console.log('e

我试图重用kendoDropDownListBox,并通过使用父级中的数据属性来查询正确的数据源,并结合switch case语句来设置数据。代码的switch case部分不包括在内,因为当正确的数据被传递给它时,它就工作了,我只是无法从data属性中提取正确的数据(如果我使用按钮传递数据,它工作得很好)

我尝试了许多方法来提取属性,包括以下内容

element.dataset[关键字名称] element.getAttribute('keyname']

如果我执行console.log('element'),我可以看到正确的数据,但是上面两个方法中的任何一个都是空的(null或未定义)

HTML:

Listbox组件

elatt变量包含以下内容:

elkey变量报告“未定义”,att变量报告“空”

我肯定我做这件事可能很难,但作为一个新的角度,我不确定有没有更好的方法来做这件事

最终,我要寻找的是一种将kendoDropdownBox作为组件重用的方法,并将使用时需要显示的数据传递给它。

ngOnInit(): 首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。 在第一个ngOnChanges()之后调用一次

ngAfterViewInit(): Angular初始化指令所在的组件视图和子视图/视图后响应。 在第一个ngAfterContentChecked()之后调用一次

您无法从父级检索数据属性,因为您正试图从ngOnInit事件访问父级。它应该在ngAfterViewInit生命周期事件中。

请参考下面的示例

ParentComponent.html

<div [attr.data-message-id]="1">
  <app-test-component></app-test-component>
</div>
输出日志


您是否尝试过这个.elRef.nativeElement.parentElement.dataset.messageId。它在控制台中给您带来了什么?给您看,它确实很奇怪#1项清楚地表明dataset在那里,然后下一行代码提示它的“未定义”(elkey)完美!谢谢您Narayanan。
import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-test-component',
  templateUrl: './test-component.component.html',
  styleUrls: ['./test-component.component.css']
})
export class TestComponentComponent implements OnInit {

  constructor(private elRef: ElementRef) {
  }


  ngOnInit() {
  }

  ngAfterViewInit(){

    console.log(this.elRef.nativeElement.parentElement);

    console.log('message id : ', this.elRef.nativeElement.parentElement.dataset['messageId']);
  }
}