Field in component becomes null between ngOnInit and click event

Issue

Typical component:

@Component (
selector: 'mycomp',
template: '<div>mycomp</div>',
)
class MyComp implements OnInit {
String testobj;
void mymeth() {
  context.callMethod('alert', [testobj]);
}
@override
ngOnInit() {
  testobj = '123';
  context.callMethod('alert', ['initialized']);
}}

placed in app root component like that:

import 'mycomp_component.dart';
import 'package:angular/angular.dart';
@Component (
selector: 'testcomp',
template: '''
<button (click)="testModeler()">load</button>
<mycomp></mycomp>''',
providers: const[MyComp],
directives: const[MyComp],
)
class TestComponent {
MyComp myComp;
TestComponent(this.myComp);
void testModeler() {
  myComp.mymeth();
}}

testobj initializes on page load, but when I click a “load” button testobj is null! Why it happens and how to make it working properly?

Also: how to diagnose problems like that in dart, is there a possibility to put a breakpoint on class or field? I don’t find a way in dartium/

Solution

Angular creates an instance per provider.

If you use

providers: const[MyComp],

this provider will hold an instance of the MyComp class. This will not be an Angular component, just an instance of the plain class. Angular won’t call ngOnInit because it is not a component.
This instance will be passed to the constructor.

Angular creates a component for <mycomp></mycomp> though and calls ngOnInit on this instance.
This is another instance than the once created by the provider.

To get hold of a reference of a component in the template you can use @ViewChild() or @ContentChild()

@Component (
  selector: 'testcomp',
  template: '''
    <button (click)="testModeler()">load</button>
    <mycomp></mycomp>''',
    directives: const[MyComp],
)
class TestComponent {
  @ViewChild(MyComp) MyComp myComp;

  TestComponent();

  void testModeler() {
    myComp.mymeth();
  }
}

How can I select an element in a component template? provides some additional explanation. It’s for TypeScript but most things should work with small syntax changes.

https://webdev.dartlang.org/angular/guide should also contain some info.

Answered By – Günter Zöchbauer

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *