Search code examples
angularweb-componentangular-components

Is there any way to have a private property in a class that is available in the HTML template in Angular?


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?


Solution

  • 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:

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

    In your second component, this method should throw an error, because title is a read only property:

    this.my.title = "other title"; 
    

    You should be able to access the value if you wanted, like this:

    console.log(this.my.title);
    

    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.

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

    Then this would work fine:

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