对于类似I18n的组件,我希望将组件内容作为字符串来获取后备值,以防我的I18n服务什么都没有,这个值应该是一个后备值.
I18n服务获取方法:
public get(key:string,defaultValue?:string,variables:Variables = {},domain?:string):string { for (let catalogue of this.catalogues) { if (catalogue.getDomains().indexOf(domain) >= 0 && catalogue.getLocale() == this.locale && catalogue.hasKey(key)) { return I18n.setVariables(catalogue.get(key,domain,defaultValue).value,variables); } } return defaultValue; }
I18nComponent:
@Component({ selector: "i18n",template: "{{text}}",}) export class I18nComponent implements OnInit { constructor(private i18n:I18n) { } @ContentChild() content:string; //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; ngOnInit():any { console.log(this.content); //Here I get 'undefined' 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.domain); } } }
用法示例:
<i18n key="FOO_KEY" domain="stackoverflow">I'm the default value !</i18n>
我知道< ng-content>< / ng-content>但只能在模板逻辑上工作,我需要一种方法来将child作为string中的字符串.
已经尝试过@ContentChild(String),但我没有定义.
另一种方法是像索引中的基本应用程序组件中的“加载…”字符串一样执行它,就像占位符一样,直到您加载所有内容.我可以为I18n做同样的事情,让花边夹在这里,直到我从服务中得到一些东西来取代它,但我不知道如何实现这一点.
您不能使用@ContentChildren()来获取整个内容.您可以添加模板变量并查询其名称:
<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); }
在调用ngAfterContentInit()之前,不会初始化myVar.
或者@ContentChild()(或@ContentChildren())可以查询类似的组件类型
<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); }
我认为这种方法对你的方法更有效
@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.domain); } } }
如果您希望i18n组件的用户能够在他们传递给< i18n>的内容中使用Angular绑定,组件和指令,那么他需要将其包装在模板中.
<i18n key="FOO_KEY" domain="stackoverflow"> <template> I'm the {{someName}}! <my-comp (click)="doSomething()"></my-comp> </template> </i18n>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。