Search code examples
angulartypescriptangular-cliangular-componentsangular7

Trouble with Angular Component in Tutorial


I'm reading Angular in Action from Manning. Chapter 2 shows me how to write my first component but the example is outdated. I can't figure out how to update it. I'm using Angular CLI version 7.1.3.

Angular CLI generates this:

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-summary',
    templateUrl: './summary.component.html',
    styleUrls: ['./summary.component.scss']
})
export class SummaryComponent implements OnInit {
    constructor() { }
    ngOnInit() {
    }
}

The book assumes that Angular CLI will generate this:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'summary',
  styleUrls: ['./summary.component.css'],
  templateUrl: './summary.component.html'
})
export class SummaryComponent {
  @Input();
}

What is the difference between @Input and OnInit? How does a person take an input example and translate it into the "OnInit" way of doing things?


Solution

  • @Input and ngOnInit are two different directives and do not conflict or replace each other.

    You can quite easily (manually) add @Input to the generated component and continue as per the book. Just ignore the ngOnInit for now until you learn to use it. It won't hurt to just leave it there.

    If you want to know what ngOnInit does, look here

    Also notice, if your example deals with the styles, then the CLI has generated sccs but the book has css. sccs should technically take all css and should just work.