Angular: One-way data binding input fields in separate components

Rumen Manev
2 min readDec 3, 2020

--

This short post is part of a series, where I share quick tips on how to do web dev stuff that I’ve struggled with, but eventually figured out. My goal is to help you discover this easier than I did.

Use case

Let’s say we have a web app with several pages. There’s some kind of flow that the user needs to go through, with different steps on different pages.

On each step, the user needs to enter some kind of information in input fields.

On one of the steps, one of the input fields has to be disabled and pre-populated with the input the user has already given on a previous step. For example, on step 1 the user enters their email address and on step 2 the user needs to fill out a username and password, in order to register, but we want the email to be used as a username. That’s why we put the email given on step 1 in the username input field on step 2, with the field disabled, so the user can see that their email is being used as a username.

How to do that

Inside the .ts file of your step 2 component, where you define your form, add a FormControl to the username input field:

loginDataForm = new FormGroup({
username: new FormControl({ value: '', disabled: this.disabled })
});

You also need to define “disabled”, below:

disabled = true;

Inside the .html of the same component, the input field should look something like this (assuming you’re using Material):

<input matInput formControlName="username" value type="text" />

In order to use information in one component given by the user in another component on a different route, you can save that information in local storage.

Once you’re saving the input data from step 1 in local storage, you can reference the information by looking up the local storage inside the component for step 2.

In your step 2 component, define a variable that takes up the value of your local storage model:

tempData: localStorageDTO = {};

Then in the body of your .ts file create the function:

setUsername() {
const usernameToEMail = this.tempAappDTO.personalData.mail;
this.loginDataForm.get('username').setValue(usernameToEMail);
}

After that, all you need to do is call the function when the component loads:

ngOnInit(): void {
this.setUsername();
}

If you have a similar use case, hope this was helpful!

If the explanation was too unclear or you need more details on how to store your data in local storage, let me know in the comments.

--

--

Rumen Manev
Rumen Manev

Written by Rumen Manev

Frontend developer with a business background

No responses yet