Angular2 Dart - Get Text inside Angular2 Component

后端 未结 1 1681
滥情空心
滥情空心 2021-01-06 13:12

I\'ve got an item component which I use inside other components, the item component typically looks like this:



        
相关标签:
1条回答
  • 2021-01-06 13:43

    With @ContentChild() or @ContentChildren() you can only query for components and directives by passing the type of these components or directives as parameter or you can query for template variables.

    If you have

    <item type="the-type">
      <div #someVar>the-text<div>
    </item>`
    

    then you can query for the div with

    @ContentChild('someVar') ElementRef someVar;
    

    If you don't want the user of your component to require to wrap the content with an element and add a specific template variable you can use a wrapper element around <ng-content>

    @Component(
        selector: 'item',
        //providers: const[String],
        template: '<div #wrapper><ng-content></ng-content></div>')
    class Item implements AfterContentInit {
    
        @ViewChild('wrapper') ElementRef wrapper;
        @Input() String type = "type-goes-here";
    
        @override
        ngAfterContentInit() {
            print(wrapper.innerHtml); // or `wrapper.text`
        }
    }
    

    Not sure yet if this issue will make this easier https://github.com/angular/angular/issues/8563

    0 讨论(0)
提交回复
热议问题