Get component child as string

前端 未结 1 1883

For an I18n-like component, I want to get a component content as string to have a fallback value in case my I18n service gets nothing, this value is supposed to be a fallb

相关标签:
1条回答
  • 2020-12-18 12:05

    You can't use @ContentChildren() to get the whole content. You can either add a template variable and query for its name:

    <i18n key="FOO_KEY" domain="stackoverflow"><span #myVar>I'm the default value !</span></i18n>
    
    @ContentChild('myVar') myVar;
    
    ngAfterContentInit() {
      console.log(this.myVar.nativeElement.innerHTML);
    }
    

    myVar will not be initialized before ngAfterContentInit() is called.

    Alternatively @ContentChild() (or @ContentChildren()) you can query for a components type like

        <i18n key="FOO_KEY" domain="stackoverflow"><my-comp>I'm the default value !</my-comp></i18n>
    
    @ContentChild(MyComponent, {read: ElementRef}) mycomp;
    
    ngAfterContentInit() {
      console.log(this.myVar.nativeElement.innerHTML);
    }
    

    I think this approach will work better for you approach

    @Component({
        selector: "i18n",
        template: "<div #wrapper hidden="true"><ng-content></ng-content><div>{{text}}",
    })
    export class I18nComponent implements OnInit {
    
        constructor(private i18n:I18n) {
        }
    
        @ViewChild('wrapper') content:ElementRef; //Here, I want to store actual value as fallback one.
    
        @Input('key') key:string;
    
        @Input('domain') domain:string;
    
        @Input('variables')
        variables:Variables = [];
    
        @Input("plural")
        plural:number;
    
        text:string;
    
        ngAfterViewInitInit():any {
            console.log(this.content.nativeElement.innerHTML);
            if (this.plural !== undefined && this.plural != null) {
                this.text = this.i18n.get(this.key, this.content, this.variables, this.domain);
            } else {
                this.text = this.i18n.getPlural(this.key, this.plural, this.content, this.variables, this.domain);
            }
        }
    }
    

    If you want the users of your i18n component to be able to use Angular bindings, components, and directives, in the content they pass to <i18n>, then he needs to wrap it in a template.

        <i18n key="FOO_KEY" domain="stackoverflow">
          <template>
            I'm the {{someName}}!
            <my-comp (click)="doSomething()"></my-comp>
          </template>
        </i18n>
    

    like explained in https://stackoverflow.com/a/37229495/217408

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