Is it better to set Angular2 @Inputs as public, or should we opt for a stricter API by keeping them private?

I am currently utilizing Angular2 with Typescript

Imagine having the following code in the template of my app component:

... 
<coffee-cup [coffee]=""
...

Here is my coffee-cup component:

@Component({
  selector: 'coffee-cup',
  ...
})
export class CoffeeCup {

  @Input() 
  public coffee = 0;

}

At this moment, I am uncertain about how to define my Input. It could be like this:

@Input()
public coffee = 0;

Or

@Input()
private coffee = 0;

Currently, I am inclining towards making the member variable coffee private.

  • I aim to establish a clear public API for the component
  • I prefer to only allow setting the coffee property through the template
  • Currently, there is no necessity for coffee to be read or set directly from the parent component. If required, I can remove the private modifier.

In my perspective, a component has two distinct APIs for interaction:

  1. The template API, which includes the @Inputs and @Outputs
  2. The Typescript API encompassing all public properties and methods

I have not yet investigated the outcome in the following scenario, it might alter the response:

  • Assume the coffee member is public. If my appComponent accesses CoffeeCup using @ViewChild and sets the coffee member, will the lifecycle hooks (like ngOnChange) activate?

To reiterate the query: Should Angular2 @Inputs remain public or can/should we enforce a more restricted API by making them private?

Answer №1

When considering API design, the use of @Input suggests a public nature. This principle applies within the context of Angular as well, where these decorators define how components can interact with each other.

The purpose of the @Input decorator, along with other meta decorators, is to inform Angular about your intentions and provide insight into the relationship between templates and component classes.

In some instances, the change detection engine utilizes these decorators. For instance, when a field marked with @Input is monitored by the change detection mechanism, it indicates that this property should be watched for changes.

<...more unique content here...>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it that the game board component is not appearing on my HTML page?

I am currently facing an issue with a loop in my Angular html file: <div class="board" #board> <div class="row" *ngFor="let row of this.board; let i = index"> <div *ngFor=" ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

What is the proper way to utilize ngIfElse in Angular 9?

Currently, I have a list of posts that are being fetched using services and displayed on the UI. There is a search box with an ID field specified in it. My goal is to render the post in a card if the provided ID exists. This functionality is working well. ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

Tips for transferring JSON data into an array in Angular

How can I pass JSON data retrieved from an API into an array and then display that information in my template? I'm not sure how to accomplish this task. An error is appearing on my console, you can view it here. This is my TypeScript file: this.api. ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Utilizing Angular 2 canActivate feature to make a promise call to connect with a remote service

Initially, I'm unsure if this approach is the most effective way to tackle the issue at hand. What I am seeking is a route guard on "/" that verifies whether the user is logged in and, if so, redirects them to "/dashboard". It's important for thi ...

Utilizing Async/Await with Node.js for Seamless MySQL Integration

I have encountered two main issues. Implementing Async/Await in database queries Handling environment variables in pool configurations I am currently using TypeScript with Node.js and Express, and I have installed promise-mysql. However, I am open to usi ...

Error: Unable to convert <> to a Fragment due to a conflict with multiple versions of prosemirror-model being loaded

While utilizing the ngx-editor in my application, everything was working smoothly until recently when I encountered an issue only on my local setup. The problem arises when attempting to press Enter to create a new line. Typing and using the toolbar still ...

Displaying nested objects within an object using React

Behold this interesting item: const [object, setObject] = useState ({ item1: "Greetings, World!", item2: "Salutations!", }); I aim to retrieve all the children from it. I have a snippet of code here, but for some reason, i ...

Align item in center of remaining space within container using Material-UI React

I am relatively new to MUI and styling HTML components, and I have a query. I'm currently utilizing the Grid feature in my React project. My goal is to achieve something similar to this (image edited in Paint, alignment may not be accurate): https://i ...

Utilizing a GLTF asset as the main Scene element in a Three.js project

I'm struggling with incorporating a gltf model as the main scene in Three.js. Specifically, I have a gltf model of an apartment that I want to load from inside and not outside the apartment. I also need the controls to work seamlessly within the apart ...

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

Verifying Angular Universal Using JSON Web Tokens

I have a project in Angular 10 Universal where I am using JWT obtained from localhost to verify requests for restricted routes. Currently, I am utilizing the following package for authentication: https://www.npmjs.com/package/@auth0/angular-jwt The issue ...

Bypass Auth0 HttpInterceptor based on certain conditions

During the transition from Firebase to Auth0, my Angular front-end application authenticates users to either Firebase or Auth0 based on their email address. I am working on configuring the Auth0 AuthHttpInterceptor provided in the Auth0 Angular SDK for SPA ...

Guide on accessing and manipulating local files using an Angular application

For my Angular 7 web app project, I'm looking to allow users to complete surveys and submit their responses. Since I don't have a database set up yet, I thought of storing the results in a local json file for now. Unfortunately, I'm facing d ...

How to pass props to customize styles in MUI5 using TypeScript

Currently, I'm in the process of migrating my MUI4 code to MUI5. In my MUI4 implementation, I have: import { createStyles, makeStyles } from '@material-ui/core'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; ty ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Guide on disabling a hyperlink in a table column under specific conditions using Angular2

I am working with a table that has 4 columns: Name, id, Dept, City. The row data and column data are provided as an array from a typescript file and I am iterating through *ngFor to display the content. Below is a snippet of my code: <tbody> < ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...