In angular2, how to call a function inside an element without mouse event? - function

Below is part of code in parent component, I already get the enable value from eventEmitter in its child component, which is enable=true.
<img src="{{currentImg}}" alt="Play Image not found" (click)="onMouseClick()">
<pause-button (isPauseBtnClicked)="enable = $event"></pause-button>
status is: {{enable}}
Then how can I assign a value for currentImg="someImg.png" after it listened the eventEmitter(enable=true)? Should I write a function? if so, how can I call that function in img tag without any mouse event?
I konw with mouse click event, things becomes easier, currentImg can be assign a value inside function.
onMouseClick() {
this.currentImg = this.clickedImg;
}

Look I don't know what you want to achieve. But writing this answer by thinking that you want to go with EventEmitter way without calling any mouseevent.
Note: Your expectation might be different. But It might help you out. If doesn't, kindly use it as a reference. I might have understood something completely different but purpose is not to guide you in wrong way
<img src="{{currentImg}}" alt="Play Image not found" (click)="onMouseClick()">
<pause-button (isPauseBtnClicked)="fire($event)"></pause-button><br>
status is: {{enable}}<br> // haven't played with status
{{currentImg}}
boot.ts
fire(arg) {
console.log('test start');
//this.animate.subscribe((value) => { this.name = value; });
this.currentImg=arg;
console.log(arg);
}
Working Plunker
PasueButton.ts
#Component({
selector: 'pause-button ',
template: `
________________________________________________________
<br>
I'm child
<br>
<img src="img path" (click)="clickMe()"/>
<= click the img
<br>
_____________________________________________________
`
,
})
export class PasueButton implements OnInit {
#Output() isPauseBtnClicked: EventEmitter = new EventEmitter();
constructor() {
console.log('Constructor called');
}
ngOnInit() {
console.log('onit strat');
}
clickMe()
{
this.isPauseBtnClicked.next('child Img path is copied');
}
}

Related

Pass data - object from child to parent Angular 6

In child component, I have a datatable, when I click on the row, I will get data and keep it in branchToDivision, I also have a button, when I hit that button, I can send branchToDivision to the parent component.
Child component
#Output() messageEvent: EventEmitter<BranchDto> = new EventEmitter<BranchDto>();
branchToDivision: BranchDto;
onSelect(record: BranchDto) {
this.branchToDivision = new BranchDto();
this.branchToDivision = record;
console.log(this.branchToDivision);
console.log(this.branchToDivision.brancH_CODE);
}
acceptBranch() {
this.onSelect(this.branchToDivision);
this.messageEvent.emit(this.branchToDivision);
this.branchModalDivision.hide();
}
Parent Component
branch: BranchDto;
getBranch(branch: BranchDto): void{
this.branch = branch;
console.log(this.branch);
console.log(this.branch.brancH_CODE);
}
Parent HTML
<branchModal #branchModal (messageEvent)="getBranch($event)" ></branchModal>
I try to log branch property but it is undefined, What's wrong? Any idea is helping me well.
This is a way to send information from child component to parent component:
parent.component.html:
<div>
<child (getData)="getData($event)"></child>
</div>
in parent.component.ts:
public getData(value): void {
console.log(value) // welcome to stackoverflow!
}
in child.component.ts:
import {Output, EventEmitter} from '#angular/core';
#Output() public getUserData = new EventEmitter<string>();
this.getUserData.emit('welcome to stackoverflow!');
I hope my help is effective ツ

Angular 5 - Auto-reload the HTML page of the specific component at some fixed intervals

The manual solutions for Auto Reloading the HTML page of a specific component:
Either by navigating to the HTML page on click.
Or calling the ngOnInit() of that component on click.
I am doing it manually using a click event from the HTML code as follows:
HTML Code: app.component.html
<button (click) = reloadPage()>
TS Code: app.component.ts
reloadPage() {
// Solution 1:
this.router.navigate('localhost:4200/new');
// Solution 2:
this.ngOnInit();
}
But I need to achieve this automatically. I hope I am clear. The page should auto-reload after some specific interval and call the ngOnInit() on each interval.
Add correct call to setInterval anywhere in your call:
setInterval(() => reloadPage(), 150000); and inside the method reloadPage put the same logic you have for the button.
An example:
Just put the reloadPage function call inside the constructor:
export class SomeComponent {
constructor() {
setInterval(() => this.reloadPage(), 150000);
}
reloadPage() {
// anything your button doeas
}
}
also note, that correct call of setInterval would be:
setInterval(() => this.reloadPage(), 150000);
Note: My answer just fixes the code you presented. But it seems there is some bigger logical misunderstanding of "reloading page" in angular and using ngOnInit

ReactJS adding onClick handler into element given an HTML string

I'm given an HTML string from an API:
<div><h1>something</h1><img src="something" /></div>
I would like to add an onClick handler onto the img tag. I thought about using regex replace, but it's highly advised against.
I'm new to React... how would you go about solving this problem?
Any links or pointing into the right direction would be highly appreciated!
EDIT
Is there a way to add a listener to all anchor tags in a react friendly way? I'm thinking then I can just check the anchor tag's children, and if there's an image element, then I can run my code block.
I think a more idiomatic React way of doing this would be to refactor this into a component, replete with it's own onClick handler, and then insert your image URL via props. Something like
class MyImg extends React.Component {
onClick() {
// foo
}
render() {
return (
<div onClick={this.onClick}>
<h1>{this.props.foo}</h1>
<img src={this.props.imgSrc} />
</div>
);
}
}
Can you update your API to return JSON instead of HTML? JSON is easier to manipulate and you can create react elements on the fly, for example, let's assume your API returns this:
{
component: 'div',
children: [
{ component: 'h1', text: 'Something here' },
{ component: 'img', src: 'something.jpg' },
],
}
If you have that kind of response is very easy to create React elements at run time, you can also add events when creating these components, for example:
class DynamicContent extends PureComponent {
onImageClick = () => {
// Do something here!
console.log('Testing click!');
}
render() {
const children = response.children;
return React.createElement(response.component, null,
React.createElement(children[0].component, null, children[0].text),
React.createElement(children[1].component, {
...children[1],
onClick: this.onImageClick, // <-- Adds the click event
}),
);
}
}
You might want to create an utility that dynamically walks through the response object and creates all the components that you need.

How many times does Angular 2 render a single page before showing it?

I'm using Angular 2 for my project. I have a simple div in my template which calls a function in my .ts file that outputs a simple text like this:
<div>{{ test() }}</div>
private test(): void {
console.log("Test text");
}
When I load a page I get the same output many times like this:
Test text
Test text
Test text
Test text
Test text
Does that mean that Angular 2 renders the template many times before it actually shows it and consequently calls function every time?
Angular renders the AppComponent and it's child components exactly once, except when you add remove parts of the DOM, then these added parts will be rendered again.
What you experience is Angulars change detection which runs quite frequently. See also Why event triggers ChangeDetection even if OnPush strategy is ON?.
It is usually a bad idea to use functions in value bindings because such functions will be called every time Angular runs change detection.
Prefer to assign the value to a property and bind to this property instead.
<div>{{ testVal }}</div>
ngOnInit() {
this.testVal = this.test();
}
private test(): string {
console.log("Test text");
return 'some string';
}
Yes It renders multiple time since ChangeDetectionStrategy is always "Default" means it check always(multiple times) for UI update
ChangeDetectionStrategy.OnPush
Use OnPush: OnPush means that the change detector's mode will be set to CheckOnce during hydration.
If you use ChangeDetectionStrategy.OnPush then it will print only once
changeDetection: ChangeDetectionStrategy.OnPush
https://angular.io/api/core/ChangeDetectionStrategy
https://plnkr.co/edit/lNXNsS?p=preview
Code Snippet
#Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'my-app',
template: `
<div>
Check Console
<h2>{{print()}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
console.log("Called Once")
}
print(): void {
console.log("I am printing only one time"):
}
}

How can I reset redux state when hitting go back in a web browser?

This is my use case:
In the WelcomeScreen I have code like this:
class WelcomeScreen extends Component {
render() {
const {
checkoutState,
} = this.props;
if (checkoutState.status === TRYING_TO_BUY) {
return this.renderPurchaseForm(plan);
}
return this.renderWelcome();
}
When the user visit /welcome, he can hit a purchase button, which will dispatch an action and set the checkoutState.status to TRYING_TO_BUY. The Welcome will be rerendered by calling renderPurchaseForm
Within renderPurchaseForm, it will render a ArticlePurchaseBlock
renderPurchaseForm() {
const { articleId } = this.props;
return (
<ArticlePurchaseBlock
articleId={articleId}
/>
)
and in the block, the class will try to update the url to reflect that it is in an input form
import { withRouter } from 'react-router';
class ArticlePurchaseBlock extends Component {
componentWillMount() {
const { history } = this.props;
history.push(URL_BUY_ARTICLE);
}
render() {
// render a redux-form
}
}
export default withRouter(ArticlePurchaseBlock);
You can see the history.push(URL_BUY_ARTICLE); is called in componentWillMount.
Now the problem is: when the user in the purchase form, if a user wants to go back to previous url (/welcome) , he can't. It is because the state of checkoutState.status is still TRYING_TO_BUY. The welcome is always rendered to the form.
Is there any where within the ArticlePurchaseBlock I can monitor the go back event and unset the state? I do not plan to use redux-saga-router yet because of time constraint.
I am using react-router v4
I designed a router for this exact problem. It's excessively difficult with react-router. https://github.com/cellog/react-redux-saga-router. For your code:
https://gist.github.com/cellog/0731f7e1ba8f9009f6b208c2bd15aa16
The entire thing can be done in 1 line of code, and your routes look almost identical to react-router, with 1 additional line for mapping param or url change to action.