"Our paths have crossed before, Dom."
- The Fate of the Furious (2017)
It's time to make our component interact with the DOM.
Alright, so the first thing I'm gonna do is remove that h1
tag from the app template, so the only thing our app holds for now is our kick-ass component. Less clutter.
app.component.html
:
<app-kick-ass></app-kick-ass>
Now, let's add some properties to our component class, so our comp and DOM actually have something to talk about:
kick-ass.component.ts
:
export class KickAssComponent implements OnInit {
alias;
age;
name;
constructor() {
this.alias = 'Hit-Girl';
this.name = 'Mindy';
}
ngOnInit() {
}
}
We've added three properties: alias, age and name. We've given two of them some values inside the constructor. Note that we refer to the property using the this
keyword. It's a class we're dealing with; not a plain method.
Now, let's add a method to get the both these values in a joined string:
export class KickAssComponent implements OnInit {
alias;
age;
name;
constructor() {
this.alias = 'Hit-Girl';
this.name = 'Mindy';
}
ngOnInit() {
}
getProfile() {
return `${this.name} is really ${this.alias}`;
}
}
It's a simple method which just returns strings stitched together. Notice we're using the ES6 template literal notation.
This looks good. But it would look even better with Typescript type checks added in. Our code now becomes:
export class KickAssComponent implements OnInit {
alias: string;
age: number;
name: string;
constructor() {
this.alias = 'Hit-Girl';
this.name = 'Mindy';
}
ngOnInit() {
}
getProfile(): string {
return `${this.name} is really ${this.alias}`;
}
}
This was just to illustrate how the code looks with and without TS. So everything doesn't look too obtuse at first glance.
We're all set to edit our template now. Currently it's:
kick-ass.component.html
<p>
kick-ass works!
</p>
Let's edit that <p>
to hold a property we just defined. To do that, we need the scary looking moustache syntax we saw earlier.
<p>
{{name}}
</p>
Basically, think of the stuff inside the double braces as code. Yup. You're writing code inside your HTML. Your paragraph should now read 'Mindy'. (the value of the property 'name').
Angular will evalute anything you write inside the double braces, not just properties. If you want, you could call a function in there.
<p>
{{getProfile()}}
</p>
And your page is now:
You see. The stuff inside {{
and }}
is bona fide js code. You call a method with the usual signature that includes parentheses.
This probably raises more questions than it answers. Can we pass parameters while calling these? What happens when the method doesn't return a string? What happens when the param signatures don't match?
All in good time. I think we should cover some more ground before going for a deep dive.