MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

slidenumbers: true

Angular Components

Marc Kapke

kapkema@gmail.com


Components


Components


Component lifecycle

inline


Lifecycle hooks


ngOnChanges hook


ngOnInit hook


ngOnDestroy


Metadata


Component example

@Component({
  selector: 'app-article-detail',
  templateUrl: './article-detail-simple.component.html',
  styleUrls: ['./article-detail-simple.component.css']
})
export class ArticleComponent implements OnInit {

  title = "article page";

  constructor(
    private articleService: ArticleService,
    public article: Article) {
  }

  ngOnInit() {
    this.articleService.getArticle("food", 7, 1).subscribe(
      article => this.article = article
    )
  }
}


Testing a component


Example test setup

describe('ArticleDetailSimpleComponent', () => {
  let component: ArticleComponent;
  let fixture: ComponentFixture<ArticleComponent>;

  beforeEach(async(() => {
     let articleServiceStub = new ArticleService(null);
     TestBed.configureTestingModule({
       imports: [],
       declarations: [ArticleComponent],
       providers: [{provide: ArticleService, useValue: articleServiceStub}, Article],
     })
       .compileComponents();
   }));

   beforeEach(() => {
     fixture = TestBed.createComponent(ArticleComponent);

     let articleService = fixture.debugElement.injector.get(ArticleService);
     spyOn(articleService, 'getArticle').and.returnValue(Observable.of(new Article().id=500));

     component = fixture.componentInstance;
     fixture.detectChanges();
   });
  //tests go here  
});

First beforeEach(async())


Second beforeEach


TestBed


configureTestingModule()

beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    });
  })

TestBed - createComponent


ComponentFixture


detectChanges()


Example tests

it('should create', () => {
  expect(component).toBeTruthy();
});

it('should have article in model on init', () => {
  expect(component.article).toEqual(new Article().id = 500)
});

it('should have title in model ', () => {
  expect(component.title).toEqual("article page")
});

it('should have title in dom', () => {
  const compiled = fixture.debugElement.nativeElement;
  let title = compiled.querySelector("p");
  expect(title.textContent).toContain(component.title);
});