gpt4 book ai didi

angular - 如何在 Angular 2 中保留我的主要组件的先前内容?

转载 作者:太空狗 更新时间:2023-10-29 17:26:38 24 4
gpt4 key购买 nike

在 Angular 1 中,我可以将任何元素定义为根元素,并且不会替换任何已编写的内联 HTML。例如 Angular 1。

<body>
<div ng-app="">
<h1><?php echo $heading_this_page;?></h1>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>

但是在 Angular 2 中,如果我这样写上面。

<body>
<ng-app>
<h1><?php echo $heading_this_page;?></h1>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</ng-app>
</body>

我用 ng-app作为主/根组件选择器,ng-app 的 innerHTML元素,被组件的 HTML 替换。

@Component({
selector: 'ng-app',
template:'<h1>App works</h1>";
directives: [UsersComponent]
})

ng-app的innerHtml现在变成<h1>App works</h1> .我要ng-app的以前内容保留。

如果这不可能,我可以做类似下面的事情吗。

<body>
<ng-app>
<h1><?php echo $heading_this_page;?></h1>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
<render-component-here></render-component-here>
</ng-app>
</body>

在哪里ng-app是我的主要组件(加载时引导),它应该在 <render-component-here></render-component-here> 中呈现其数据元素(而不是通过替换以前的内容本身)

最佳答案

添加<ng-content></ng-content>在你的组件模板中

@Component({
selector: 'ng-app',
template:'<div><h1>App works</h1><ng-content></ng-content></div>';
directives: [UsersComponent]
})

检查 toddmotto解释

请记住,在根组件(正在引导的组件)中包含文本将不适用于 ng-content .

<body>
<ng-app>loading...</ng-app>
</body>

NgApp 组件

@Component({
selector: 'ng-app',
template: `
<h1>App component</h1>
<my-apps>This is the text by ng-content</my-apps>
<ng-content></ng-content>

`,
})

在所有其他组件中包含内容将有效。

检查工作 plunker

index.html 中的

loading... 将始终替换为 ng-app组件

因此,即使您提到了 <ng-content></ng-content>,您也是同样的情况。它不会工作。如果你想包括它,你还必须有另一个父组件,并且你必须有 <ng-app>现在,里面 <ng-app>你需要有 <ng-content>

关于angular - 如何在 Angular 2 中保留我的主要组件的先前内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44674135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com