有没有办法在Angular中的HTML模板中提供的类中拥有私有属性



我正在制作一些自定义组件,这些组件将在我的项目的不同部分(可能不止一个项目(中使用,我希望在这些组件的HTML模板中呈现一些属性,但也不能作为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

不可能向组件的HTML模板公开Angular组件上的私有属性。

您可以通过提供get方法而不是set方法将该属性公开为只读属性:

private _title:string='TITLE'; 
get title(): {
return this._title;
}

在第二个组件中,这个方法应该抛出一个错误,因为title是只读属性:

this.my.title = "other title"; 

如果你想的话,你应该能够访问这个值,比如:

console.log(this.my.title);

但是,将无法设置。

这里需要注意的是,如果您不使用文字,而是使用数组或对象,则即使不设置主属性,也可以修改对象属性。

private _myObject = {}; 
get myObject(): {
return this._myObject;
}

然后这会很好:

this.my.myObject.title = "other title"; 

最新更新