⊗jsagPmCMCC 60 of 97 menu

Child Components in Angular

As mentioned at the very beginning of the tutorial, in Angular the entire project is divided into components. In the previous lessons, we worked only with the main component created by default. Let's now learn how to create child components.

The code for new components is automatically generated by Angular using a special terminal command: generate component. After the word component, you need to write the name of your new component. Let's say we want to generate the user component:

ng generate component user

After running the command, we will see that we have a new folder app/user. It will contain all the standard files of the component.

In the file with the component user.component.ts a component decorator will be automatically created:

@Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] })

Also in this file the component class will be automatically created:

export class UserComponent { }

Now our child component needs to be connected to the parent. Let the parent be the app component, which was initially present when the framework was installed. Let's import our component into it:

import { UserComponent } from './user/user.component';

In the component decorator, in the imports key, we specify our imported component:

@Component({ selector: 'app-root', imports: [UserComponent], // here is templateUrl: './user.component.html', styleUrls: ['./user.component.css'] })

Now we can display the contents of the child component in the parent. To do this, in the file with the parent template, you need to write a special tag, the name of which is specified in the selector property of the @Component decorator of the child. In our case, this is the app-user tag. Let's write it in the parent template:

some text <app-user></app-user>

Generate the ProductComponent component. Connect this component to the main component of your project.

Make changes to the child component template. Make sure they are applied in the browser.

Change the CSS styles of the child component. Make sure they are applied in the browser.

In the child component, create properties name and price. Display their values ​​in the child component template.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline