为Angular根组件/模块指定@Input()参数

jen*_*ent 14 angular-bootstrap angular

我有3个根组件,由root引导AppModule.

你如何@Input()为其中一个组件指定参数?

也不

<app-modal [id]="'hard-coded value'"></app-modal>
<app-modal [id]="constantExportedByAppmodule"></app-modal>
Run Code Online (Sandbox Code Playgroud)

通过AppModalComponent以下方式获取:

@Input() id: string;
Run Code Online (Sandbox Code Playgroud)

这是未定义的.

Gré*_*art 25

据我所知,你不能将@Input()传递给bootstraped组件.

但您可以使用其他方法来做到这一点 - 将值作为属性传递.

index.html:

<my-app myAttribute="myAttributeValue">
    <div>Loading...</div>
</my-app>
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

@Component({
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']
})
export class AppComponent {
    constructor(private elementRef:ElementRef) {
        let myAttribute = this.elementRef.nativeElement.getAttribute('myAttribute');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我唯一能想到的:`this.myattribute = this.sanitizer.sanitize(SecurityContext.HTML, this.elementRef.nativeElement.getAttribute('myattribute'))` (3认同)

Sam*_*Sam 5

正如@GrégoryGossart所说,你不能像引导组件那样正常传递@Input数据.

这是因为@Input预计来自角度分量.所以,如果您的根应用程序直接在HTML中加载/引导它没有参考@Input会提供什么,我想.

好的做法评论了许多Angular文档,可能因为它的特定行为,你应该只引导一个根应用程序.我认为你的选择是添加一个你引导的根应用程序,然后导入你的其他应用程序(3)并将其作为模板使用.然后正常传递@Input.真的没什么特别的.

我认为如果您决定需要引导所有这些数据并需要外部数据,那么另一个选项可能是将数据从@Injectable传递到您的根应用程序.但我觉得它更多地涉及特定目的.

编辑:我花了一些时间来找到我过去一天读过的这个博客以及为什么我说@Injectable.这是作者的优点,但有趣的东西.在引导Angular 2时提供外部数据

  • 我们将角度组件添加到传统asp.net Web表单块中的各个位置,作为重构的基础.在这个阶段,一个根组件不是一个选项而不是一次性重写整个批次. (3认同)