有什么方法可以在 Angular 的 HTML 模板中提供的类中拥有私有属性吗?
我正在制作一些自定义组件,这些组件将在我的项目的不同部分(可能不止一个项目)中使用,并且我希望有一些属性可以在这些组件的 HTML 模板中呈现,但也不能作为 < code>public 对于可能包含该组件的其他组件。
例如:
我的通用组件
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnInit {
title:string='TITLE'; // public because otherwise the template can't use it
}
在其模板中包含 MyComponent
的其他组件
@Component({
selector: 'other-component',
templateUrl: './other-component.component.html',
styleUrls: ['./other-component.component.scss'],
})
export class OtherComponent implements OnInit {
@ViewChild(MyComponent) my:MyComponent;
...
fun(){
this.my.title = "other title"; // this is what I don't want to happen
}
...
}
有没有办法避免 OtherComponent
能够使用 MyComponent.title
?
I'm making a few custom components that will be used in different parts of my project (possibly more than one project) and I wanted to have a few properties to render in the HTML template of those components, but also not be available as public
for other components that might include the said component.
For example:
My generic component
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnInit {
title:string='TITLE'; // public because otherwise the template can't use it
}
Other component that includes MyComponent
in its template
@Component({
selector: 'other-component',
templateUrl: './other-component.component.html',
styleUrls: ['./other-component.component.scss'],
})
export class OtherComponent implements OnInit {
@ViewChild(MyComponent) my:MyComponent;
...
fun(){
this.my.title = "other title"; // this is what I don't want to happen
}
...
}
Is there a way to avoid OtherComponent
to be able to use MyComponent.title
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无法将 Angular 组件上的私有属性公开给组件的 HTML 模板。
您可以通过提供 get 方法而不是 set 方法将该属性公开为只读属性:
在第二个组件中,此方法应该抛出错误,因为 title 是只读属性:
您应该能够如果需要,可以访问该值,如下所示:
但是,将不可设置。
这里需要注意的是,如果您不使用文字,而是使用数组或对象,则即使不设置主属性,也可以修改对象属性。
那么这样就可以正常工作了:
It is not possible to expose private properties on an Angular component to the component's HTML Template.
You might be able to expose that property as a read only property by supplying a get method, but not a set method:
In your second component, this method should throw an error, because title is a read only property:
You should be able to access the value if you wanted, like this:
But, will not be settable.
The caveat here is that if you're not using a literal, instead an array or object, the object properties can be modified even without setting the main property.
Then this would work fine: