Swap - Public API ( @Input, @Output )

For times, when you want to pass something from Parent component to child component, and receive an event back

The documentation does a great job outlining this - https://stenciljs.com/docs/decorators

@Prop() declares an exposed property/attribute @State() declares an internal state of the component @Watch() declares a hook that runs when a property or state changes @Event() declares a DOM event the component might emit

and let's go over them one by one.

@Prop - [ replacement for @Input() ]

Children components should not know about or reference parent components, so Props should be used to pass data down from the parent to the child.

Components need to explicitly declare the Props they expect to receive using the @Prop() decorator.

It's important to know, that a Prop is by default immutable from inside the component logic. Once a value is set by a user, the component cannot update it internally.

For more - https://stenciljs.com/docs/properties#prop-decorator

@State - [ additional better feature ]

This is used to manage internal data for a component. This means that a user cannot modify this data from outside the component, but the component can modify it however it sees fit.

Any changes to a @State() property will cause the components render function to be called again.

Not all variables need to be marked as @State. Only the ones that are supposed to affect the UI for the component ( internal loader, bookmarked icon change etc. )

This is an additional feature, which is not present in Angular explicitly. With angular, this is achieved by the fact that things added on this, and also referenced in the template would only get added for Change Detection.

@Event - [ replacement for @Output() ]

Components can emit data and events using the Event Emitter decorator. To dispatch Custom DOM events for other components to handle, use the @Event() decorator.

Step 1. Define @Event() todoCompleted: EventEmitter;

Step 2. Emit event this.todoCompleted.emit(todo);

Step 3. Handling event - From parent

<todo-list onTodoCompleted={ev => this.someMethod(ev)} />

@Watch - [ replacement for ngOnChanges() , sort of ... ]

When a user updates a property, Watch will fire the method it's attached to, and pass that method the new value of the prop along with the old value. Watch is useful for validating props or handling side effects.

The Watch decorator does not fire when a component initially loads.

@Watch('activated') 
watchHandler(newValue: boolean, oldValue: boolean) { 
    console.log('The new value of activated is: ', newValue); 
}

This watch is set up to look for changes to the 'activated' property.

Last updated

Was this helpful?