Creating our first component – the FileUpload component

The Import Image link on our navigation has to actually do something, so we are going to write a component that will be displayed inside a dialog. As we are going to upload a file, we are going to call this FileUpload, and creating it is as simple as running the following Angular CLI command:

ng generate component components/fileupload
We can shorten these standard Angular commands if we want, so we can use ng g c instead of ng generate component.

This command creates four files for us:

  • fileupload.component.html: The HTML template for our component.
  • fileupload.component.scss: Anything that we need to convert into CSS for our component.
  • fileupload.component.spec.ts: Now, spec.ts files are used when we want to run unit tests against our Angular applications. Properly testing web applications is outside the scope of this book as it's a book in its own right.
  • fileupload.component.ts: The logic for the component.
Running the ng command to generate the component also results in it being added into the declarations section in app.module.ts.

When we open up fileupload.component.ts, the structure roughly looks like this (ignoring the imports at the top):

@Component({
selector: 'atp-fileupload',
templateUrl: './fileupload.component.html',
styleUrls: ['./fileupload.component.scss']
})
export class FileuploadComponent implements OnInit {
ngOnInit() {
}
}

Here, we can see that Angular is making full use of TypeScript features that we have already looked at. In this case, FileuploadComponent has a Component decorator that tells Angular that we use atp-fileupload when we want to use a FileuploadComponent instance in our HTML. As we are using a separate HTML template and style, the other parts of the @Component decorator identify where those elements are. We could define styles and templates directly in this class, but in general, it's better to separate them out into their own files.

We can see our naming convention here, having specified atp when we created our application. It's a good idea to use something meaningful. When working in a team, you should find out what the standard is that your team follows and, if there is no standard, you should take the time to agree on how you want this to be named up front.

One of the features of the dialog is that it will show us a preview of the image that the user selects. We are going to separate the logic for reading the image from the component to keep a nice and clean separation of concerns going on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.219.166